为什么我在 TypeScript 中收到“类型‘字符串’不能用作索引类型”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41709887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:32:41  来源:igfitidea点击:

Why I'm getting "Type 'String' cannot be used as an index type" error in TypeScript

typescript

提问by JoelParke

I have a large amount of js code that uses a number of assoicative arrays that allow very fast access to objects. So I tried to port this code and failed. So clearly I don't understand TS well enough yet.

我有大量的 js 代码,它们使用了许多允许非常快速地访问对象的关联数组。所以我试图移植这个代码并失败了。很明显,我对 TS 的理解还不够好。

I have hunted for an the answer to this question and found suggestions to create an interface etc... but this seems a bit off the track.

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

So tried the seeming obvious:

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

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

where MyObject - simplified:

其中 MyObject - 简化:

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

And I would believe that:

我会相信:

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

would be fine... YET I see the lovely TS2342 error (An index expression argument must be of type 'string', 'number', or 'any') which makes no sense to me since getId() is a 'string'. It doesn't seem like this should be that hard. So your help would be greatly appreciated...

会很好......然而我看到了可爱的 TS2342 错误(索引表达式参数必须是“字符串”、“数字”或“任何”类型)这对我来说没有意义,因为 getId() 是一个“字符串” . 这似乎不应该那么难。所以你的帮助将不胜感激......

回答by Paarth

Use lowercase stringfor the type of MyObject._id

使用小写string的类型MyObject._id