TypeScript의 유틸리티 타입(Utility Types)은 기존 타입을 변형하여 새로운 타입을 만들 수 있게 해준다.
이를 통해 복잡하고 유연한 타입을 쉽게 정의할 수 있으며, 코드 재사용성과 타입 안전성을 높인다.
<T>T의 모든 프로퍼티를 선택적으로 만드는 타입을 구성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',
});
console.log(todo1) //{ title: 'organize desk', description: 'clear clutter' }
console.log(todo2) //{ title: 'organize desk', description: 'throw out trash' }
<T>T의 모든 프로퍼티를 읽기 전용(readonly)으로 설정한 타입을 구성interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: 'Delete inactive users',
};
todo.title = 'Hello'; // 오류: 읽기 전용 프로퍼티에 재할당할 수 없음
T에서 프로퍼티 K의 집합을 선택해 타입을 구성interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
T에서 모든 프로퍼티를 선택한 다음 K를 제거한 타입을 구성interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
T에서 U에 할당할 수 있는 모든 속성을 제외한 타입을 구성type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T2 = Exclude<string | number | (() => void), Function>; // string | number
T의 프로퍼티의 집합 K로 타입을 구성interface PageInfo {
title: string;
}
type Page = 'home' | 'about' | 'contact';
const x: Record<Page, PageInfo> = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};
T에서 U에 할당 할 수 있는 모든 속성을 추출하여 타입을 구성type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () => void
<T>T 함수 타입의 반환 타입을 구성function getUser() {
return { name: 'Alice', age: 25 };
}
type User = ReturnType<typeof getUser>;
const user: User = { name: 'Alice', age: 25 };
<T>T 함수 타입의 매개변수 타입을 튜플로 구성function log(message: string, userId: number): void {
console.log(`${userId}: ${message}`);
}
type LogParams = Parameters<typeof log>;
const params: LogParams = ['Hello, world!', 1];
log(...params); // 1: Hello, world!
<T>Awaited<T>는 Promise의 결과 타입을 추론하는 유틸리티 타입async function fetchData(): Promise<string> {
return "Hello, world!";
}
// fetchData 함수의 반환 타입 추론
type FetchDataType = Awaited<ReturnType<typeof fetchData>>;
const data: FetchDataType = await fetchData();
console.log(data); // "Hello, world!"