83

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.

Max
  • 1,054
  • 1
  • 12
  • 20
JoelParke
  • 2,676
  • 2
  • 24
  • 38
  • Possible duplicate of [Typescript: difference between String and string](http://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string) –  Jan 18 '17 at 01:25
  • 11
    `String` is different from `string`, that is, `_id: string;` should work. You need `String` only when you have to use `new` with it, that is, almost never. – artem Jan 18 '17 at 01:25
  • 1
    By the way, the term "associative array" is used in neither JavaScript nor TypeScript. –  Jan 18 '17 at 01:26

1 Answers1

178

Use lowercase string for the type of MyObject._id

Paarth
  • 9,687
  • 4
  • 27
  • 36