유틸리티 타입
맵드 타입 기반의 유틸리티 타입 1 - Partial, Required, Readonly
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
type Partial<T> = {
[key in keyof T]?: T[key];
};
const draft: Partial<Post> = {
title: "제목 제목",
content: "초안 ...",
};
type Required<T> = {
[key in keyof T]-?: T[key];
};
const withThumbnailPost: Required<Post> = {
title: "한입 타스 후기",
tags: ["TS"],
content: "",
thumbnailURL: "http://...",
};
type Readonly<T> = {
readonly [key in keyof T]: T[key];
};
const readonlyPost: Readonly<Post> = {
title: "보호된 게시글",
tags: [],
content: "",
};
맵드 타입 기반의 유틸리티 타입 2 - Pick, Omit, Record
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
type Pick<T, K extends keyof T> = {
[key in K]: T[key];
};
const legacyPost: Pick<Post, "title" | "content"> = {
title: "옛날 글",
content: "옛날 컨텐츠",
};
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
const noTitlePost: Omit<Post, "title"> = {
content: "",
tags: [],
thumbnailURL: "",
};
type Record<K extends keyof any, V> = {
[key in K]: V;
};
type ThumbnailLegacy = {
large: {
url: string;
};
medium: {
url: string;
};
small: {
url: string;
};
watch: {
url: string;
};
};
type Thumbnail = Record<
"large" | "medium" | "small",
{ url: string; size: number }
>;
조건부 타입 기반의 유틸리티 타입 - Exclude, Extract, ReturnType
type Exclude<T, U> = T extends U ? never : T;
type A = Exclude<string | boolean, boolean>;
type Extract<T, U> = T extends U ? T : never;
type B = Extract<string | boolean, boolean>;
function funcA() {
return "hello";
}
function funcB() {
return 10;
}
type ReturnType<T extends (...args: any) => any> = T extends (
...args: any
) => infer R
? R
: never;
type ReturnA = ReturnType<typeof funcA>;
type ReturnB = ReturnType<typeof funcB>;
[참고]
한 입 크기로 잘라먹는 타입스크립트
- Section 10. 유틸리티 타입 강의를 듣고 정리한 내용입니다.