Search
Duplicate

[TypeScript] 유틸리티 타입 (Pick, Omit, Partial, Record 등)

간단소개
Partial, Pick, Omit에 대해 알아보자
팔만코딩경 컨트리뷰터
ContributorNotionAccount
주제 / 분류
TypeScript
Scrap
태그
9 more properties
react-router 코드에서 갑자기 등장한 Pick! import에도 없고 대체 이게 뭐지…?
export type Navigator = Pick<History, "go" | "push" | "replace" | "createHref">; interface NavigationContextObject { basename: string; navigator: Navigator; static: boolean; } export const NavigationContext = React.createContext<NavigationContextObject>( null! );
TypeScript
복사
엥 대체 Pick이 뭐지…? 검색해보니 타입스크립트의 Utility Type이라고 한다. 나... 아직 타입스크립트를 많이 모르는구나…ㅜㅜ
이번 기회에 모든 유틸리티 타입들을 정리해보자! 아래 제공된 모든 예제는 TypeScript공식 Docs에서 참고하였다!

Pick<Type, keys>

v2.1 Constructs a type by picking the set of properties Keys(string literal or union of string literals) from Type
전달받은 Type에서 string literal 혹은 union of string으로 받은 keys를 뽑아서 타입을 생성한다.
interface Todo { title: string; description: string; completed: boolean; } type TodoPreview = Pick<Todo, "title" | "completed">; const todo: TodoPreview = { title: "Clean room", completed: false, };
TypeScript
복사
예제를 보면 Todo는 title, description, completed를 가지고 있는데 여기서 Pick을 활용해 TodoPreview는 title과 completed만을 가지는 타입으로 지정할 수 있다.
즉, 위 react-router코드에서는 History에서 go, push, replace, createHref만 가져와서 만든 새로운 타입을 Navigator로 지정한 것이다.
History interface를 보고싶다면. github 보기

Omit<Type, Keys>

v3.5 Constructs a type by picking all properties from Typeand then removing Keys (string literal or union of string literals)
전달받은 Type에서 string literal 혹은 union of string으로 받은 keys제외한 타입을 생성한다.
type TodoInfo = Omit<Todo, "completed" | "createdAt">; const todoInfo: TodoInfo = { title: "Pick up kids", description: "Kindergarten closes at 5pm", }; todoInfo;
TypeScript
복사
Omit은 Pick과 반대라고 생각하면 된다! 전달받은 keys를 제외한 타입을 생성한다.

Partial<Type>

v2.1 Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.
Partial은 전달받은 Type의 모든 하위 집합을 나타내는 타입을 생성한다.
interface Todo { title: string; description: string; } function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { return { ...todo, ...fieldsToUpdate }; } const todo1 = { title: "organize desk", description: "clear clutter", }; const todo2 = updateTodo(todo1, { description: "throw out trash", });
TypeScript
복사
즉, Partial<Todo> 를 하게되면 Todo로 만들 수 있는 모든 하위 집합 타입 {}, {title: string}, {description: string}, {title : string, description: string} 중 하나가 올 수 있는 것이다.
실제로 history와 같은 오픈소스 라이브러리를 뜯어보면 아래와 같이 사용하는 것을 알 수 있다.
export interface Path { pathname: Pathname; search: Search; hash: Hash; } export type To = string | Partial<Path>;
TypeScript
복사
Partial을 활용해서 dummy 생성 함수 만들기 작업을 하다보면 더미 데이터를 생성해서 테스트를 진행해야할 때가 있다. 타입스크립트로 작성되어 있다면 아주 간단하게 함수를 생성할 수 있다. 만드는 시점에 원하는 값을 넣은 더미 데이터가 필요할 수 있기 때문에 Partial을 활용해서 원하는 값을 활용해 더미를 만들 수 있는 함수를 만들어 보았다.
export const createDummyTodo = (data: Partial<TodoResponse>): TodoResponse => { return { id: data.id ?? Math.random().toString(), title: data.title ?? 'title', content: data.content ?? 'content', createdAt: data.createdAt ?? Date.now().toString(), updatedAt: data.updatedAt ?? Date.now().toString(), }; }; export const createDummyTodos = (numbers: number): TodoResponse[] => { return Array.from(Array(numbers), () => createDummyTodo({})); };
TypeScript
복사

Record<Keys, Type>

v2.1 Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.
Record는 keys로 이루어진 object 타입을 만드는데, 각 프로퍼티들이 전달받은 Type이 된다.
interface CatInfo { age: number; breed: string; } type CatName = "miffy" | "boris" | "mordred"; const cats: Record<CatName, CatInfo> = { miffy: { age: 10, breed: "Persian" }, boris: { age: 5, breed: "Maine Coon" }, mordred: { age: 16, breed: "British Shorthair" }, }; cats.boris;
TypeScript
복사
즉, 위 예제에서는 cats는 CatName으로 이루어진 object이고 각 프로퍼티들은 CatInfo 타입이 되는 것이다.
정리한 내용보다 훨씬 많은 Utility Type들이 존재한다. 실제로 쓰이는 예제를 볼 때마다 조금씩 추가할 예정이다!!

Reference