【问题标题】:Using multer and express with typescript使用 multer 和 express 和 typescript
【发布时间】:2019-10-22 19:37:57
【问题描述】:

背景

我正在制作一个简单的网站,用户可以在其中上传图片。 我正在使用 Node/React/Multer/Typescript

问题

app.post('/admin/uploads', async (req, res) => {
  uploadHandler(req, res, (err) => {
    ...
    if ( req.files.companyImage !== undefined ) {
      ...
    }
    res.sendStatus(201);
  });
});

typescript intellisense 显示如下错误。

Property 'companyImage' does not exist on type '{ [fieldname: string]: File[]; } | File[]'.
Property 'companyImage' does not exist on type '{ [fieldname: string]: File[]; }'.ts(2339)

但是,我不明白为什么这是错误的。我认为files 对象的类型为{ [fieldname: string]: File[]; }。这意味着files 对象可以具有字符串属性。

所以我用简单的例子进行测试。

type myType = {
  [fieldName: string]: number
}

let req: myType = {
  a: 333,
  b: 344
}

console.log(req.a);
console.log(req.c); // undefined but intellisense don't show error

我不知道为什么files 对象不能有companyImage 属性。

请检查。

【问题讨论】:

    标签: node.js typescript express multer


    【解决方案1】:

    我通过Object.assign(req.files) 解决了它,然后你可以将它作为一个对象处理: console.log(s.image[0].path);

    【讨论】:

      【解决方案2】:

      我不知道你是否成功解决了你的问题,但我也遇到了同样的问题,我不得不明确告诉 TypeScript 我的 req.files 属性的类型,如下所示:

      const files = req.files as { [fieldname: string]: Express.Multer.File[] };
      

      请注意,由于我使用的是upload.fields(...),我并没有指定req.files 也可以是简单的Express.Multer.File[]

      【讨论】:

      • Express' 没有导出的成员 'Multer'
      • npm install --save-dev @types/multer 拥有它
      猜你喜欢
      • 1970-01-01
      • 2016-06-14
      • 2016-10-22
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多