上級 › keyof typeofで作ったキーの型は、存在しないキーを渡すとエラーになる › パターン4
keyof typeofで作ったキーの型は、存在しないキーを渡すとエラーになる
keyof typeof objは、実行時のオブジェクトobjが実際に持つキーだけを表すunion型(リテラル型の集合)になります。
1 const fruits = { apple: 1, banana: 2 }; 2 type FruitKey = keyof typeof fruits; 3 function getCount(key: FruitKey): number { 4 return fruits[key]; 5 } 6 console.log(getCount(________)); ^
main.ts(6,22): error TS2345: Argument of type '"cherry"' is not assignable to parameter of type '"apple" | "banana"'.
空欄を埋めてコンパイルを通す
FruitKeyはfruitsが実際に持つキーだけを表します。"cherry"はfruitsに存在しないキーです。
次の問題