- Parial
- Required
- Readonly
- Pick
- Record
- Exclude
- Extract
- Omit
- NonNullable
- Parameters
- ConstructorParameters
- ReturnType
- InstanceType
- ThisType
Parial
Partial: 기존 객체의 속성을 전부 옵셔널로 만드는 함 수
type MyPartial<T> = {
[P in keyof T]?: T[P];
};
type Result = MyPartial<{ a: string; b: number }>;
Required
Required: 기본 객체의 속성을 전부 필수로 만드는 함수
type MyRequired<T> = {
[P in keyof T]-?: T[P];
};
type Result = MyRequired<{ a?: string; b?: number }>;
Readonly
기본 객체의 속성을 전부 읽기 전용으로 만드는 함수
type MyReadonly<T> = {
readonly [P in keyof T]: T[P];
};
type Result = MyReadonly<{ a: string; b: number }>;
Pick
기본 객체에서 지정한 속성만 추리는 함수
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Result = MyPick<{ a: string; b: number; c: number }, "a" | "b">;
Record
type MyRecord<K extends keyof any, T> = {
[P in K]: T;
};
type Result = MyRecord<"a" | "b", string>;
Exclude
Exclude: 어떤 타입에서 지정한 타입을 제거하는 타입
컨디셔널 타입 활용
type MyExclude<T, U> = T extends U ? never : T;
type Result = MyExclude<1 | "2" | 3, string>;
// type Result = 1 | 3
Extract
Extract: 어떤 타입에서 지정한 타입을 추출하는 타입
컨디셔널 타입 활용
type MyExtract<T, U> = T extends U ? T : never;
type Result = MyExtract<1 | "2" | 3, string>;
Omit
Omit: 특정 객체에서 지정된 속성을 제거하는 타입
Pick, Exclude
type MyOmit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
type Result = MyOmit<{ a: "1"; b: 2; c: true }, "a" | "c">;
NonNullable
null과 undefined를 제거하는 nullable 타입
type MyNonNullable<T> = T extends null | undefined ? never : T;
type Result = MyNonNullable<string | null | undefined>;
type MyNonNullable<T> = T & {};
type Result = MyNonNullable<string | null | undefined>;
Parameters
ConstructorParameters
ReturnType
InstanceType
ThisType
메서드들에게 this를 한 방에 주입하는 타입
type Data = { money: number };
type Methods = {
addMoney(amount: number): void;
};
type Obj = {
data: Data;
methods: Methods & ThisType<Data & Methods>;
};
const obj: Obj = {
data: {
money: 1,
},
methods: {
addMoney(amount) {
this.money += amount;
},
},
};