keyofについて
keyofについて
keyofにオブジェクトを指定すると、そのオブジェクトのいずれかのキー(プロパティ名)を許容するUnion Typeが返却される
interface SampleInterface { a: string; b: number; c: boolean; } type Keys = keyof SampleInterface; const aKey: Keys = 'a'; const bKey: Keys = 'b'; const cKey: Keys = 'c'; const dKey: Keys = 'd'; // compile error
T[K]について
T[K] でT に対してKのtypeを取得できる
type typeA= SampleInterface ['a'];
とすると、typeAのtypeは string になる。 SampleInterface['b'] とすれば number。 T[K] は、keyof T を満たすtypeになる。
typeofについて
typeofを使うと対象の変数の型を取得できる
let val1 = "abc"; console.log(typeof val1); // "string"を出力 let val2: typeof val1 = 1; // string型にnumber型の値を代入しようとしてエラーになる
let person1 = { name: "jack", age: 18 }; // "object"を出力するが、実態は"{ name: string, age: number}" console.log(typeof person1); // ageがないためコンパイルエラー let person2: typeof person1 = { name: "Michael" };
const const1 = "abc"; // "string"を出力するが、実態は"type xxx = 'abc';" console.log(typeof const1); const const2: typeof const1 = "def"; // "abc"以外を代入しようとしてエラーになる
keyof typeofで何をやっているのか段階的に確認する
元コード
const PromiseStatus = { PENDING: 1, FULFILLED: 2, REJECTED: 9, } as const; type PromiseStatusType = typeof PromiseStatus[keyof typeof PromiseStatus]; const a: PromiseStatusType = 1; const b: PromiseStatusType = 2; const c: PromiseStatusType = 9; //const d: PromiseStatusType = 0; // Compile Error
Step1
const PromiseStatus = { PENDING: 1, FULFILLED: 2, REJECTED: 9, } as const; type TypeOfPromiseStatus = typeof PromiseStatus; type KeyOfPromiseStatus = keyof TypeOfPromiseStatus; type PromiseStatusType = TypeOfPromiseStatus[KeyOfPromiseStatus]; const a: PromiseStatusType = 1; const b: PromiseStatusType = 2; const c: PromiseStatusType = 9; //const d: PromiseStatusType = 0; // Compile Error
Step2
const PromiseStatus = { PENDING: 1, FULFILLED: 2, REJECTED: 9, } as const; type TypeOfPromiseStatus = { readonly PENDING: 1; readonly FULFILLED: 2; readonly REJECTED: 9; }; type KeyOfPromiseStatus = "PENDING" | "FULFILLED" | "REJECTED"; type PromiseStatusType = 1 | 2 | 9;; const a: PromiseStatusType = 1; const b: PromiseStatusType = 2; const c: PromiseStatusType = 9; //const d: PromiseStatusType = 0; // Compile Error