How to flip a string indexed array in TypeScript?

I defined a static property as such:

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

but when I try to use for... offrom the answer given here: TypeScript for-in statement

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

I get an error message:

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

If I switch to use for in, the error will disappear and valuewill be printed as any.

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

What is the actual type valuein this case? Ideally, I would like to iterate over all the values ​​in the colorsByName property, either in pairs, or just get the return types MyColorClass.

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

What are my options?

+10
source share
2

- MyColorClass.

, , , :

const colors = Object.keys(MyClass.colorsByName).map(key => MyClass.colorsByName[key]);

, , :

function propsToArray<T>(obj: { [index: string]: T; } | { [index: number]: T; }) {
    return Object.keys(obj).map(prop => obj[prop]);
}

:

for (const color of propsToArray(MyClass.colorsByName)) {
    // use color here
}

. , MyClass.

Object.values

Object.values():

for (const color of Object.values(MyClass.colorsByName)) {
    // use color here
}

, .

+11

for..in

Typescript (Typescript: ) , for..in .

for..in , ... , .

:

// 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...
}

, :

// 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...
}
+2

Source: https://habr.com/ru/post/1628560/


All Articles