Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate Over String Indexed Array In TypeScript?

I have defined a static property as such:

private static colorsByName: { [index: string]: MyColorClass}

but when I attempt to use for... of from the answer listed here: TypeScript for-in statement

for(let value of MyClass.colorsByName) {
    ...
}

I get an error:

Type { [index: string]: MyColorClass; } is not an array type or a string type.

If I switch over to using for in, the error goes away, but value is typed as any.

for(let value of MyClass.colorsByName) {
    ...
}

What is the actual type of value in this case? Ideally I'd like to loop through all values in the colorsByName property, either in a pair approach, or just to get MyColorClass types returned.

for(let value of MyClass.colorsByName) {
    // value: MyColorClass
}

What are my options?

like image 207
Daryl Avatar asked Feb 12 '16 19:02

Daryl


1 Answers

for..in

When looking at the Typescript documentation (Typescript: Iterators and Generators), we see that the for..in syntax will iterate over the keys of the object.

for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

We can use that to our advantage to index into our object and get the strongly typed value:

// Go through each key of the indexed object:
for (const key in indexedObject)
{
   // Get the indexed item by the key:
   const indexedItem = indexedObject[key];
   // Now we have the item.

   // Use it...
}

Solution

We can use that to get an elegant solution to the question:

// Go through each named color:
for (const colorName in colorsByName)
{
   // Get the strongly typed color with this name:
   const color = colorsByName[colorName]; // : MyColorClass
   // Now we have the the strongly typed color with this name.

   // Paint the world in a techni-colour rainbow...
}
like image 126
Luke Machowski Avatar answered Oct 01 '22 23:10

Luke Machowski