
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
type ReadOnly<T> = {
readonly [P in keyof T]: T[P];
};
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
type User = {
name: string;
password: string;
address: string;
phone: string;
};
type UserPartial = {
name?: string;
password?: string;
address?: string;
phone?: string;
};
type ReadonlyUser = {
readonly name: string;
readonly password: string;
readonly address: string;
readonly phone: string;
};
-위의 세가지 User related types 를 define 하면서, 코드가 많이 중복 된다는 것을 알수가 있다. 이를 해결 하기 위해 다음과 같이 Mapped types 를 사용 할 수 있다.
{[P in K] :T}
{ readonly [P in K]? :T}
{ [ P in K ] : T }
{ [ P in K ] ?: T }
{ [ P in K ] -?: T }
{ readonly [ P in K ] : T }
{ readonly [ P in K ] ?: T }
{ -readonly [ P in K ] ?: T }
type Temp = {a: string; b: number; c: boolean };
type T1 = { [P in "x" | "y"]: number };
// {x: number, y: number }
type T2 = { [P in "x" | "y"]: P };
// { x: "x", y: "y" }
type T3 = { [P in "a" | "b"]: Temp[P] };
// { a: string, b: number }
type T4 = { [P in keyof Temp]: Temp[P] };
// {a: string, b: number, c: boolean }
type MyPartial<T> = {
[P in keyof T]?: T[P];
};
type UserPartial = MyPartial<User>;
type MappedTypeWithNewKeys<T> = {
[K in keyof T as NewKeyType]: T[K]
}
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
interface Person {
name: string;
age: number;
location: string;
}
type LazyPerson = Getters<Person>;
// {
// getName: () => string;
// getAge: () => number;
// getLocation: () => string;
// }// Exclude 를 이용한 "kind" property 제거
type RemoveKindField<T> = {
[K in keyof T as Exclude<K, "kind">]: T[K]
};
interface Circle {
kind: "circle";
radius: number;
}
type KindlessCircle = RemoveKindField<Circle>;
// type KindlessCircle = {
// radius: number;
// };
//Exclude utility type 은 다음과 같이 생겼다
type Exclude<T, U> = T extends U ? never : T;