이 두 연산자는 기존 타입과 값으로부터 타입을 파생하게 해줍니다 — 타입 레벨 프로그래밍의 기반입니다.
keyof — 객체 타입 키들의 union
ts
interface User { id: number; name: string; }
type UserKey = keyof User; // "id" | "name"
typeof — 값의 타입
ts
config = { : , : };
= config;
이 두 연산자는 기존 타입과 값으로부터 타입을 파생하게 해줍니다 — 타입 레벨 프로그래밍의 기반입니다.
interface User { id: number; name: string; }
type UserKey = keyof User; // "id" | "name"
config = { : , : };
= config;
(타입 위치에서의) typeof는 런타임 값의 추론된 타입을 포착하므로, 타입을 따로 적을 필요가 없습니다.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ann" };
getProp(user, "name"); // string 반환
getProp(user, "age"); // ❌ 오류: "age"는 user의 키가 아님
여기서 K extends keyof T는 key를 실제 키들로 제한하고, T[K](indexed access type)는 그 키의 정확한 값 타입을 돌려줍니다. 오타가 컴파일 오류가 됩니다.
const Roles = { Admin: "admin", User: "user" } as const;
type Role = typeof Roles[keyof typeof Roles]; // "admin" | "user"
keyof와 typeof는 값의 세계와 타입의 세계를 연결합니다.
타입 안전한 프로퍼티 접근, config/상수로부터의 타입 파생(단일 진실 공급원)을 떠받치며, mapped type과 conditional type의 빌딩 블록입니다.
병행하는 타입 정의를 손으로 유지하지 않도록 해주는 방법입니다.