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

时间:2018-10-28 04:05:59

标签: typescript typescript3.0

我有以下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给我以下错误:

  

元素隐式地具有“ any”类型,因为类型“ Set”没有   索引签名。

我试图更改各种编译设置,但是没有用。 有什么办法可以在代码中修复它?

错误屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

手册中的此示例与如何使用集无关。这行

pets["species"] = "mammals";

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

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

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

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

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

pets["species"] = "mammals"; // ok
// or simply
pets.species = "mammals"; 
相关问题