Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

I have a large amount of JavaScript code that uses a number of associative arrays that allow very fast access to objects. So I tried to port this code and failed. Clearly, I don't understand TypeScript well enough yet.

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

So I tried the seemingly obvious:

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

where MyObject - simplified:

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

And I would believe that:

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

That 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. Your help would be greatly appreciated.

like image 734
JoelParke Avatar asked Jan 18 '17 01:01

JoelParke


1 Answers

Use lowercase string for the type of MyObject._id

like image 179
Paarth Avatar answered Sep 20 '22 08:09

Paarth