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