Utility Types

김병엽·2024년 9월 26일

Utility Type

TypeScript의 유틸리티 타입(Utility Types)은 기존 타입을 변형하여 새로운 타입을 만들 수 있게 해준다.

이를 통해 복잡하고 유연한 타입을 쉽게 정의할 수 있으며, 코드 재사용성과 타입 안전성을 높인다.


Partial<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' }

Readonly<T>

  • T의 모든 프로퍼티를 읽기 전용(readonly)으로 설정한 타입을 구성
interface Todo {
    title: string;
}

const todo: Readonly<Todo> = {
    title: 'Delete inactive users',
};

todo.title = 'Hello'; // 오류: 읽기 전용 프로퍼티에 재할당할 수 없음

Pick<T, K>

  • T에서 프로퍼티 K의 집합을 선택해 타입을 구성
interface Todo {
    title: string;
    description: string;
    completed: boolean;
}

type TodoPreview = Pick<Todo, 'title' | 'completed'>;

const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
};

Omit<T, K>

  • T에서 모든 프로퍼티를 선택한 다음 K를 제거한 타입을 구성
interface Todo {
    title: string;
    description: string;
    completed: boolean;
}

type TodoPreview = Omit<Todo, 'description'>;

const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
};

Exclude<T, U>

  • 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

Record<K, T>

  • 타입 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' },
};

Extract<T, U>

  • T에서 U에 할당 할 수 있는 모든 속성을 추출하여 타입을 구성
type T0 = Extract<"a" | "b" | "c", "a" | "f">;  // "a"
type T1 = Extract<string | number | (() => void), Function>;  // () => void

ReturnType<T>

  • T 함수 타입의 반환 타입을 구성
function getUser() {
    return { name: 'Alice', age: 25 };
}

type User = ReturnType<typeof getUser>;

const user: User = { name: 'Alice', age: 25 };

Parameters<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!

Awaited<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!"

Reference

스파르타코딩클럽

profile
선한 영향력을 줄 수 있는 개발자가 되자, 되고싶다.

0개의 댓글