spa900
spa900

Reputation: 947

Javascript array type with defined indexes?

With typescript, apparently it is possible to have an Array() type item where you specify the index of that array as an ID. While I always assumed this was only possible in the Object() type. Example:

items: String[] = []
items["someid"] = new SomeClass()
console.log(items)

Returns:

items:[someid: SomeClass]

Although I like this idea, is it ok to use it like this?

Upvotes: 3

Views: 61

Answers (1)

justMe
justMe

Reputation: 664

Actually, array can only have numerical indexes. However remember that every array is an object as well. Thus, you are assigning 'someid" as a new property to the items object. Equivalent of

const items = []; //items.length is 0 items.someid = {}; //items.length is still zero

If you want key => value property then use a Map

Upvotes: 1

Related Questions