Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multer and express with typescript

Background

I'm making a simple website in which a user can upload an image. I'm using Node/React/Multer/Typescript.

Problem

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

typescript intellisense shows error like below.

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

But, I cannot understand why this is error. I think files object has type { [fieldname: string]: File[]; }. This means files object can have property which is string.

So I test with simple example.

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

I don't know why files object cannot have companyImage property.

Check please.

like image 805
Byeongin Yoon Avatar asked Jun 07 '19 09:06

Byeongin Yoon


1 Answers

I don't know if you successfully resolved your issue, but I had the same and had to explicitly tell TypeScript the type of my req.files property like this:

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

Note that, since I'm using upload.fields(...), I'm not specifying that req.files can also be a simple Express.Multer.File[].

like image 179
Michael Tremblay Avatar answered Nov 03 '22 16:11

Michael Tremblay