TypeScript中用for in遍历对象的属性

ts遍历对象报错误:

TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ a: number; b: number; }’.   No index signature with a parameter of type ‘string’ was found on type ‘{ a: number; b: number; }’.

代码:

let arr = {
  a: 1,
  b: 2
};

for (const n in arr) {
  console.log(n, arr[n]);
}

解决办法为修改tsconfig.json,允许索引:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

 

 

 

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |