
객체타입에서 객체의 모든 키값들을 유니온 타입으로 반환해준다.
keyof연산자는 객체 타입에 사용할 수 있으며 자바스크립트에는 존재하지 않다.
type People = {
name: string;
age: number;
};
type P = keyof People; //"age" | "name" 타입이 된다.
let ex: P = "age"; // 가능
let err: P = "name1"; // err
People타입은 name | age타입이 된다. (literal type)
type PeopleEx = {
[key: string]: string;
};
type Pex = keyof PeopleEx;
let ex01: Pex = "example"; // 가능
let ex02: Pex = 2; // 숫자로된 키를 문자열로 변환하여 처리한다. (JavaScript 객체 동작 사이의 호환성을 유지를위함)
기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법이다.
- 예시 #1
// mapped types type Car = { color: boolean; model: boolean; price: boolean | number; }; type TypeChanger<T> = { [key in keyof T]: string; // in은 왼쪽이 오른쪽에 들어있는지 체크 }; type 타입 = TypeChanger<Car>; let 객체: 타입 = { color: "red", model: "benz", price: "3억", };타입은 color, model, price 속성을 가지고 있으며 전부 string타입이 된다.