TypeScript - 유틸리티 타입 정리(Pick, Omit, Partial, Record, ...)

신태일·2024년 10월 16일
export type Navigator = Pick<History, "go" | "push" | "replace" | "createHref">;

interface NavigationContextObject {
  basename: string;
  navigator: Navigator;
  static: boolean;
}

export const NavigationContext = React.createContext<NavigationContextObject>(
  null!
);

낯선 타입인 Pick이 눈에 먼저 뜬다. JavaScript에서 forEach,map, 그리고 findfilter 같은 배열을 다루는데 편리하게 이용가능한 루프 헬퍼 함수를 지원하듯이, 타입스크립트에서도 타입 변경을 쉽고 용이하게 하기 위해 헬퍼 함수처럼 Utility Type을 제공한다.

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,
};

예제를 보면 Todo는 title, description, completed를 가지고 있는데 여기서 Pick을 활용해 TodoPreview는 title과 completed만을 가지는 타입으로 지정할 수 있다.

Omit<Type, Keys>


v3.5 Constructs a type by picking all properties from Type and 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: "Kindergarden closes at 5pm",
};

todoInfo;

Partial


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",
});

즉, 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>;
  • Partial을 활용해서 dummy 생성 함수 만들기 작업을 하다보면 더미 데이터를 생성해서 테스트를 진행해야할 때가 있다. 타입스크립트로 작성되어 있다면 아주 간단하게 함수를 생성할 수 있다. 만드는 시점에 원하는 값을 넣은 더미 데이터가 필요할 수 있기 때문에 Partial을 활용해서 원하는 값을 활용해 더미를 만들 수 있는 함수를 만들어 보자.
    export const createDummyTodo = (data: Partial<TodoResponse>): RodoResponse => {
    	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)

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;

즉, 위 예제에서는 cats는 CatName으로 이루어진 object이고 각 프로퍼티들은 CatInfo 타입이 되는 것이다.

📘 타입스크립트 유틸리티 타입 💯 총정리 (+응용)

profile
노원거인

0개의 댓글