My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement.
I've searched for solutions and come across suggestions to create an interface, but that doesn't seem quite right.
So, I attempted the following:
class Foo {
allObjects: MyObject[];
constructor() {
this.allObjects = [];
}
}
where MyObject
- simplified:
class MyObject {
_id: String;
public getId(): String {
return this._id;
}
}
And I assumed that:
myObjectInstance: MyObject;
fooInstance.allObjects[myObjectInstance.getId()] = myObjectInstance;
It seemed like a reasonable approach... However, I encountered the
TS2342 error (An index expression argument must be of type 'string', 'number', or 'any')
, even though getId()
returns a string
. This issue is puzzling to me as it should not be this complicated. Your assistance would be greatly appreciated.