Vladimir Venegas
Vladimir Venegas

Reputation: 4213

How can I define an object based array in TypeScript?

In Javascript, I can define a collection using an object, something like this:

var myArray = {};
myArray['some-key1'] = new CustomObject('param1');
myArray['some-key2'] = new CustomObject('param2');
myArray['some-key3'] = new CustomObject('param3');

In TypeScript, can I have a collection based on object's properties, like in Javascript?

Another question, if I have 100 elements in one collection, what would be faster - storing these items in a classic array (myarray.push(instanceObj)), or storing them as properties of objects?

Upvotes: 0

Views: 101

Answers (1)

thedayturns
thedayturns

Reputation: 10842

If you have a fixed number of keys, the best thing to do is:

const myObject = {
    "some-key1": new CustomObject("param1"),
    "some-key2": new CustomObject("param2"),
    "some-key3": new CustomObject("param3"),
}

Note that now even something like this typechecks:

myObject["some-key1"] // TypeScript correctly infers the type to be CustomObject!

If you can't do that, the best way is to use an index type:

let myObject: { [key: string]: CustomObject };

which indicates to TypeScript that myObject maps strings to CustomObjects.

Another question, if I have 100 elements in one collection, what would be faster - storing these items in a classic array (myarray.push(instanceObj)), or storing them as properties of objects?

It really depends on what you're planning to do with the array/object. What's your use case?

Upvotes: 1

Related Questions