본문 바로가기

Dev

Typescript의 자주쓰는 유틸리티 타입들 (Pick, Omit, Partial, Exclude, Record)

▶︎ Pick

특정 타입의 속성을 뽑아 새로운 타입을 생성한다.

interface Profile {
    id: string
    address: string
}

type ProfileId = Pick<Profile, 'id'>

// 위와 같은 타입
// type ProfileId = {
//     id: string
// }

 

▶︎ Omit

Pick과 반대로 특정 타입의 속성을 제외한 나머지를 뽑아 새로운 타입을 생성한다.

interface Profile {
    id: string
    address: string
}

type ProfileAddress = Omit<Profile, 'id'>

// 위와 같은 타입
// type ProfileAddress = {
//     address: string
// }

 

▶︎ Partial

특정 타입의 속성을 Optialnal하게 바꾼 새로운 타입을 생성한다.

interface Profile {
    id: string
    address: string
}

type OptionalProfile = Partial<Profile>

// 위와 같은 타입
// type ProfileAddress = {
//     id?: string
//     address?: string
// }

const nothing: OptionalProfile = {}
const onlyId: OptionalProfile = { id: 'id' }
const onlyAddress: OptionalProfile = { address: 'address' }
const profile: OptionalProfile = { id: 'id', address: 'address' }

 

▶︎ Exclude

유니언 타입을 구성하는 특정 타입을 제외하여 새로운 타입을 생성한다.

type NullableIds = number | string | null
type NotNullIds = Exclude<NullableIds, null>

const a: NullableIds = null
const b: NotNullIds = null // 👈 Error❗️

 

▶︎ Record

타입 1개를 속성의 key로 받고 다른 타입 1개를 속성의 value의 타입으로 받아 새로운 타입을 생성한다.

type Profile = Record<'id' | 'address', string>

// 위와 같은 타입
// type Profile = {
//     id: string
//     address: string
// }
interface PhoneSpec {
    name: string
    introducedYer: number
    colors: string[]
    capacities: string[]
}
type PhoneNames = 'iPhone 15' | 'Samsung Galaxy S23'

type Phones = Record<PhoneNames, PhoneSpec>

// 위랑 같은 타입
// type Phones = {
//     "iPhone 15": PhoneSpec
//     "Samsung Galaxy S23": PhoneSpec
// }