본문 바로가기
프로그래밍/타입스크립트

타입스크립트 - 유틸리티 타입

by Programmer.Junny 2025. 2. 18.

제네릭, 맵드, 조건부 타입 등의 조작 기능을 이용해 실무에서 자주 사용되는 타입을 미리 만들어 놓은 것이다.

이전 시간에 알아보았던 '조건부 타입', '제네릭 조건부 타입', '분산적 조건부 타입', 'infer 조건부 타입' 기반으로 미리 라이브러리화 해둔 것들이다.

Partial<T>

특정 객체 타입의 모든 프로퍼티를 선택적 프로퍼티로 바꿔주는 타입

interface Post {
    title: string,
    tags: string[],
    content: string,
    thumbnailURL? : string,
}
const draft: Partial<Post> = {
    title: '나중에',
    content: '초안',
}

Required<T>

특정 객체 타입의 모든 프로퍼티를 필수 프로퍼티로 바꿔주는 타입

const withThumbnailPost : Required<Post> = {    //모든 프로퍼티가 필수로 구현해야함
    title: 'title',
    tags: ['ts'],
    content: '',
    thumbnailURL: 'https://..',
}

Readonly<T>

특정 객체 타입에서 모든 프로퍼티를 읽기 전용 프로퍼티로 만들어주는 타입

const readonlyPost: Readonly<Post> = {
    title: '보호된 글',
    tags: [],
    content: '',
    thumbnailURL: '',
}
// readonlyPost.content = '수정불가';

모든 프로퍼티가 readonly가 되어 위와 같이 수정이 불가해진다.

Pick<T, K>

객체 타입으로부터 특정 프로퍼티만 골라내는 타입

const legacyPost: Pick<Post, 'title' | 'content'> = {
    title: '옛날 글',
    content: '옛날 컨텐츠',
}

title, content 프로퍼티만을 뽑아낸 새로운 타입으로 생성

Omit<T, K>

객체 타입으로부터 특정 프로퍼티를 제거하는 타입

const noTitlePost: Omit<Post, 'title'> = {
    content: '옛날 컨텐츠',
    tags: [],
    thumbnailURL: ''
}

title 프로퍼티를 제거할 수 있다.

Record<K, V>

공통된 프로퍼티를 객체 내에 정의할 수 있게 된다.

type ThumbnailLegacy = {
    large: {
        url: string,
    },
    medium: {
        url: string,
    },
    small: {
        url: string,
    },
    watch: {
        url: string,
    },
}

위의 코드에서 url이 공통적으로 기술되어있다.

type Thumbnail = Record<'large' | 'medium' | 'small', { url: string }>;

첫 번째 파라미터는 생성할 객체이름, 두 번째 파라미터에서 프로퍼티를 기술하면 된다.

Exclude<T, U>

T에서 U를 제거하는 타입

type A = Exclude<string | boolean, boolean>

A는 string, boolean 중 boolean을 제거하므로 string이 된다.

Extract<T, U>

T에서 U를 추출하는 타입

type B = Extract<string | boolean, boolean>

B는 string, boolean 에서 boolean을 추출하므로 boolean이 된다.

ReturnType<T>

함수의 반환값 타입을 추출하는 타입

function funcA() {
    return 'hello';
}

function funcB() {
    return 10;
}

type ReturnA = ReturnType<typeof funcA>;    //string
type ReturnB = ReturnType<typeof funcB>;    //number

 

이 외에도 NonNullable, Parameters, ConstructorParameters 등등 다양한 유틸리티 타입들이 있다.

최근댓글

최근글

skin by © 2024 ttuttak