简体   繁体   中英

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}

I am unable to add elements in my object in typescript.



const bodyData = [
  {
    propName: "name",
    value: "secondName",
  },
  {
    propName: "surname",
    value: "nothing",
  },
];

const updatedData = {};

bodyData.forEach(({ propName, value }) => (updatedData[propName] = value));

console.log(updatedData);

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.

14 bodyData.forEach(({ propName, value }) => (updatedData[propName] = value)); ~~~~~~~~~~~~~~~~~~~~~

at createTSError (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:513:12) at reportTSError (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:517:19) at getOutput (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:752:36) at Object.compile (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:968:32) at Module.m._compile (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:1056:42) at Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Object.require.extensions.(anonymous function) [as.ts] (/home/mycomputer/MyTrailProjects/typescript-rest-shop/node_modules/ts-node/src/index.ts:1059:12) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function. Module._load (internal/modules/cjs/loader.js:585:3)

You have to declare type for updateData like this:

const updatedData: {
  [key: string]: string;
} = {};

You can try this either:

const updatedData: Record<string, string> = {};

or set:

"noImplicitAny": true

in tsconfig.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM