私は静的プロパティを次のように定義しました:
private static colorsByName: { [index: string]: MyColorClass}
しかし、ここにリストされている答えからfor... of
を使おうとすると: TypeScript for-inステートメント
for(let value of MyClass.colorsByName) {
...
}
エラーが発生します:
タイプ{[インデックス:文字列]:MyColorClass; }は配列型でも文字列型でもありません。
for in
の使用に切り替えると、エラーは消えますが、value
はany
と入力されます。
for(let value of MyClass.colorsByName) {
...
}
この場合のvalue
の実際のタイプは何ですか?理想的には、ペアアプローチで、または単にMyColorClass
型を返すために、colorsByNameプロパティのすべての値をループしたいと思います。
for(let value of MyClass.colorsByName) {
// value: MyColorClass
}
私のオプションは何ですか?
これは配列ではなく、文字列キーとタイプ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()
:を使用することもできます。
_for (const color of Object.values(MyClass.colorsByName)) {
// use color here
}
_
ただし、それを使用する場合は、 polyfill を追加する必要がある場合があります。
TypeScriptのドキュメント( TypeScript:Iterators and Generators )を見ると、for..in構文がオブジェクトのキーを反復処理することがわかります。 。
for..inは、繰り返されるオブジェクトのキーのリストを返しますが、for..ofは、繰り返されるオブジェクトの数値プロパティの値のリストを返します。
これを利用して、オブジェクトにインデックスを付け、強く型付けされた値を取得できます。
// 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...
}