【问题标题】:Why am I getting "Type 'String' cannot be used as an index type" error in TypeScript?为什么我在 TypeScript 中收到“Type 'String' cannot be used as an index type”错误?
【发布时间】:2017-06-02 06:27:12
【问题描述】:

我有大量的 JavaScript 代码,这些代码使用大量关联数组,可以非常快速地访问对象。所以我试图移植这段代码并失败了。显然,我对 TypeScript 的理解还不够深入。

我一直在寻找这个问题的答案,并找到了创建界面等的建议,但这似乎有点偏离轨道。

所以我尝试了看似显而易见的:

     class Foo {
       allObjects: MyObject[];
        constructor() {
         this.allObjects = [];
       }
    }

MyObject 的位置 - 简化:

     class MyObject {
         _id: String;
         public getId(): String {
            return this._id;
         }
     }

我相信:

     myObjectInstance: MyObject;
     fooInstance.allObjects[myObjectInstance.getId()] = myObjectInstance;

那很好...但是我看到了可爱的TS2342 error (An index expression argument must be of type 'string', 'number', or 'any'),这对我来说毫无意义,因为getId()string。这似乎不应该那么难。非常感谢您的帮助。

【问题讨论】:

  • Stringstring 不同,即_id: string; 应该可以工作。只有在必须使用new 时才需要String,也就是说,几乎从不需要。
  • 顺便说一句,“关联数组”一词在 JavaScript 和 TypeScript 中都没有使用。

标签: typescript


【解决方案1】:

MyObject._id 的类型使用小写的string

【讨论】:

猜你喜欢
  • 2022-12-02
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
相关资源
最近更新 更多