0

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?

3
  • Use Map class, see stackoverflow.com/questions/37894517/… Commented Dec 21, 2016 at 20:18
  • Another option is to have a object with subobjects. Commented Dec 21, 2016 at 20:23
  • 1
    var myArray: {[key: string]: CustomObject} = {} Commented Dec 21, 2016 at 20:31

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.