Pick<T, K>
interface Post {
title: string;
tags: string[];
content: string;
thumbnailURL?: string;
}
// 직접 구현
type Pick<T, K extends keyof T> = {
// K extends 'title'|'tags'|'content'|'thumbnailURL'
// number extends 'title'|'tags'|'content'|'thumbnailURL' ❌
[key in K]: T[key];
};
const legacyPost: Pick<Post, "title" | "content"> = {
title: "옛날 글",
content: "옛날 컨텐츠",
};
Pick<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>>;
// T = Post, K = 'title'
// Pick<Post, Exclude<keyof Post, 'title'>>
// Pick<Post, Exclude<'title'|'tags'|'content'|'thumbnailURL', 'title'>>
// Pick<Post, 'tags'|'content'|'thumbnailURL'>
// 제목이 없는 글
const noTitlePost: Omit<Post, "title"> = {
content: "",
tags: [],
thumbnailURL: "",
};
Record<K, V>
type ThumbnailLegacy = {
large: {
url: string;
};
medium: {
url: string;
};
small: {
url: string;
};
watch: {
url: string;
};
...
};
// 직접구현
type Record<K extends keyof any, V> = {
[key in K]: V;
};
type Thumbnail = Record<
"large" | "medium" | "small" | "watch",
{ url: string }
>;
→ 실무에서 많이 사용된다.
→ 동일한 패턴을 갖는 객체 타입을 쉽게 정의할 수 있다.