
제네릭, 맵드 타입,조건부 타입 등의 타입 조작 기능을 이용해 실무에서 자주 사용되는 타입을 만들어 놓은 것
맵드 타입
기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법을 의미한다.
마치map()API 함수를 타입에 적용한 것과 같은 효과를 가진다.
특정 객체 타입의 모든 프로퍼티를 선택적 프로퍼티로 바꿔주는 타입
interface Post {
title: string;
tags: strng[];
content: string;
thumbnailURL?: string;
}
type Partial<T> = {
[key in keyof T]? T[key];
}
const draft: Partial<Post> = {
title: '',
content: '',
}
특정 객체 타입의 모든 프로퍼티를 필수 프로퍼티로 바꿔주는 타입
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
type Required<T> = {
[key in keyof T]-?: T[key];
}
const withThumbnailPost: Required<Post> = {
title: '',
tags: '',
content: '',
thumbnailURL: '',
}
특정 객체의 타입에서 모든 프로퍼티를 읽기 전용 프로퍼티로 만들어주는 타입
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?:string;
}
type Readonly<T> = {
readonly [key in keyof T]: T[key];
}
const readonlyPost: Readonly<Post> = {
title: '',
tags: '',
content: '',
}
Pick<T, K>
객체 타입으로부터 특정 프로퍼티만 딱 골라내는 타입
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
type Pick<T, K extends keyof T> = {
[key in K]: T[key];
}
const lagacyPost: Pick<Post, 'title' | 'content'> = {
title: '옛날 글',
content: '옛날 컨텐츠',
}
Omit<T, K>
객체 타입으로부터 특정 프로퍼티를 제거하는 타입
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
const noTitlePost: Omit<Post, 'title'> = {
content: '',
tags: [],
thumbnailURL: '',
}
Record<K, V>
객체 타입을 만들어주는 타입
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?:string;
}
type Record<K extends keyof any, V> = {
[key in K]: V;
}
type Thumnail = Record<'large' | 'medium' | 'small', {url: string}>;
//type ThumnailRegacy = {
// large: { url: string };
// medium: { url: string };
// small: { url: string };
// watch: { url: string };
//}
Exclude<T, U>
T에서 U를 제거하는 타입
type Exclude<T, U> = T extends U ? never : T;
type A = Exclude<string | boolean, boolean>;
// 1. Exclude<string, boolean>
// 2, Exclude<boolean, boolean>
// 3. string | never
// 4. string
Extract<T, U>
T에서 U를 추출하는 타입
type Extract<T, U> = T extends U ? T : never;
type B = Extract<string | boolean, boolean>
// 1. Extract<string, boolean>
// 2. Extract<boolean, boolean>
// 3. boolean
ReturnType<T>
함수의 반환값 타입을 추출하는 타입
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : never;
function funcA() {
return 'hello';
}
function funcB() {
return 10;
}
type ReturnA = ReturnType<typeof funcA>
type ReturnB = ReturnType<typeof funcB>