代码之家  ›  专栏  ›  技术社区  ›  Teoman shipahi

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

  •  0
  • Teoman shipahi  · 技术社区  · 6 年前

    我有以下tsc:

    tsc --version
    Version 3.1.3
    

    {
      "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给了我以下错误:

    索引签名。

    我试图改变各种编译设置,但没有工作。 有没有办法在代码中修复它?

    错误屏幕截图:

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  0
  •   artem    6 年前

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

    pets["species"] = "mammals";
    

    不会给集合添加任何内容,它只是集合 species 属性。如果您使用 pets.has("species") 之后,它会回来 false [] 符号。

    --noImplicitAny 物种

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

    或者你可以申报 的属性 pets intersection type Set 施工单位:

    let pets: Set<string> & {species?: string} = new Set(["Cat", "Dog", "Hamster"]);
    
    pets["species"] = "mammals"; // ok
    // or simply
    pets.species = "mammals"; 
    
        2
  •  0
  •   Amin Kamalinia    6 年前

    for (let pet of pets) 请使用

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