Chin Chin - 2 months ago 24
TypeScript Question

Error TS2342: An index expression argument must be of type 'string', 'number', or 'any'

I have some places in my code that look like this:

var array = [];
MyClass myObject = new MyClass();
array[myObject] = "something";


Basically I'm using objects as keys in my array. I did not think much about it since it feels natural, the code compiles fine, and I have not encountered any bugs because of this.

Today I made a code push on an unrelated section of the code and Travis complained:

error TS2342: An index expression argument must be of type 'string', 'number', or 'any'.


on the line
array[myObject] = "something";


I believe this is due to a recent update of
tsc
. Anyway, it brings this problem to my attention, and now I'm not sure what I've been doing is correct:


  • What happens when you use objects as array keys? Do they get converted into string? If so, is the string made from an object supposed to be unique (like the hash value of the object)?

  • In short, am I doing it the wrong way? If so, what should I do to fix this problem?


Answer

Basically I'm using objects as keys in my array.

Bad idea. JavaScript doesn't support objects as keys. It calls toString on objects to get a string representation before indexing.

Fix : use a makeString function. Checkout : https://github.com/basarat/typescript-collections#a-sample-on-dictionary for an example