Home > other >  typescript error - type string cant be used to index object
typescript error - type string cant be used to index object

Time:10-16

I'm still pretty noob to typescript. I'm trying to get busboy working on my server. I have this block of code that gives me the error.

 const bb = busboy({ headers: req.headers });
   
 const uploads = {};
 const tmpdir = os.tmpdir();
 const fields = {}

 bb.on("field", (fieldname, val) => {
     fields[fieldname] = val
   console.log(`Processed field ${fieldname}: ${val}.`);
 });

the ts error im getting is on fields[fieldname]

CodePudding user response:

When you declare the variable const fields = {};, Typescript infers the type to object.

To fix your issue, you need to define a type of your variable explicitly.

const fields: Record<string, string> = {};
  • Related