keyof
The keyof operator takes an object type and produces a string or numeric literal union of its keys.
type Point = { x: number; y: number }; type P = keyof Point;
type P is the same type as “x” | “y”
If the type has a string or number index signature, keyof will return those types instead.
type Arrayish = { [n: number]: unknown }; type A = keyof Arrayish; // type A = number type Mapish = { [k: string]: boolean }; type M = keyof Mapish; // type M = string | number
M is
string | number
— this is because JavaScript object keys are always coerced to a string.※ 인덱스 시그니처(Index Signature)는 { [Key: T]: U } 형식으로
객체가 여러 Key를 가질 수 있으며, Key와 매핑되는 Value를 가지는 경우 사용한다.
typeof
TypeScript adds a
typeof
operator you can use in a type context
to ref to the type of a variable or property.
let s = "hello"; let n: typeof s; // let n: string
combined with other type operators, you can use typeof to conveniently express many patterns.
function f() { return { x: 10, y: 3 }; } type P = ReturnType<typeof f>; // wrong: type P = ReturnType<f>;
Remember that values and types aren’t the same thing. To refer to the type that the value f has,
we use typeof.
기본적으로 값은 “값 공간”에 존재한다.
값 공간에 있는 값에 typeof 연산자를 적용하여 값 공간의 값을 “타입 공간”에서 타입으로
이용할 수 있다.
응용하기
ValueOf
type ValueOf<T> = T[keyof T];
이는 다음과 같이 사용할 수 있다.
type Foo = { a: string, b: number }; type ValueOfFoo = ValueOf<Foo>; // string | number
ValueOf를 사용하지 않는다면 아래와 같이도 사용할 수 있다.
const coords = { 바위: '0', 가위: '-142px', 보: '-284px', } as const; // readonly type a = typeof coords[keyof typeof coords]; // "0" | "-142px" | "-284px"