generated at
keyof T
keyof T で、 T のpropertyのUnion型を取得できる





T がrecordの時
TypeScript
type Person = { name: string; age: number; }; type A = keyof Person; // "name" | "age"
ts
type Hoge = { foo(): void; }; type A = keyof Hoge // foo
ts
type Hoge = { [key: string]: void; }; type A = keyof Hoge // string | number
使用例


T がarray, tupleの時
中身のunionではなく、indexのunionになっていることに注意mrsekut
ts
type tuple = readonly ['a', 'b', 'c', 'd']; type tupleKeys = keyof tuple; const v1: tupleKeys = 'a'; // error. indexの話なのでerrorになる。わかる。 const t1: tupleKeys = 1; // ok. わかる const t6: tupleKeys = 6; // ok. わからん. なぜか?
なぜ、tupleのときに、要素数を超えてもエラーにならないか?
これは keyof tuple の中身を覗いたらわかるmrsekut
type tupleKeys = keyof tuple; と書いただけじゃ中身が見えないが、
こう書くと見える
ts
type tuple = readonly ['a', 'b', 'c', 'd']; type A = { [k in keyof tuple]: 4 }; /** * type A = { * [x: number]: 4; * readonly 0: 4; * readonly 1: 4; * readonly 2: 4; * readonly 3: 4; * length: 4; * toString: 4; * toLocaleString: 4; * concat: 4; * ... 19 more ...; * [Symbol.iterator]: 4; * } */
1行目の [x: number] のせいmrsekut