元素隐式具有 'any' 类型,因为类型 'Set<string>' 没有索引签名

Element implicitly has an 'any' type because type 'Set<string>' has no index signature

我有以下 tsc:

tsc --version
Version 3.1.3

和tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./",
    "lib": ["es2015", "dom"],
    "types": ["mocha", "node"],
    "typeRoots": [
      // add path to @types
      "node_modules/@types"
    ],
    "rootDir": "./",
    "watch": false,
    "downlevelIteration": true,
    "inlineSourceMap": true,
    "strict": true
  },
  "exclude": ["node_modules", "typings/browser.d.ts", "typings/browser"]
}

和文档中的示例代码:https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Iterators%20and%20Generators.md#forof-vs-forin-statements

function SymbolIterator() {
  let pets = new Set(["Cat", "Dog", "Hamster"]);
  pets["species"] = "mammals";

  for (let pet in pets) {
    console.log(pet); // "species"
  }     
  // "downlevelIteration": true (tsconfig.json)
  for (let pet of pets) {
    console.log(pet); // "Cat", "Dog", "Hamster"
  }
}

SymbolIterator();

tsc 给我以下错误:

Element implicitly has an 'any' type because type 'Set' has no index signature.

我尝试更改各种编译设置但没有奏效。 有什么方法可以在代码中修复它吗?

错误屏幕截图:

亲爱的朋友,不要使用 for (let pet of pets) 请使用

 pets.forEach(r=>{ 
   console.log(r); // "Cat", "Dog", "Hamster"
 });

手册中的这个例子不是关于如何使用集合的。这一行

pets["species"] = "mammals";

不会向集合中添加任何内容,它只是在集合对象上设置 species 属性。如果您之后使用 pets.has("species") 检查集成员资格,它将 return false。在 javascript 中,集合以及其他所有内容都继承自对象,您可以使用 [] 表示法以这种方式在任何对象上设置任何 属性。

编译器给你一个错误,因为你用 --noImplicitAny 选项指定了更严格的类型检查。此选项不允许访问和设置未声明的对象属性,因此您不能添加 species 属性 以这种方式设置对象。

如何修复代码取决于您希望代码执行的操作。如果你想不加修改地编译它,你必须关闭 --noImplicitAny 选项(或者你可以忽略错误 - 编译器无论如何都会生成 javascript 代码,除非你打开了 --noEmitOnError 选项).

或者您可以使用 intersection typepets 对象声明 species 属性。它必须是可选的,因为当使用 Set 构造函数创建对象时它不存在:

let pets: Set<string> & {species?: string} = new Set(["Cat", "Dog", "Hamster"]);

pets["species"] = "mammals"; // ok
// or simply
pets.species = "mammals";