utility Type

이아론·2024년 3월 18일
post-thumbnail

유틸리티 타입

유틸리티 타입은 타입스크립트가 자체적으로 제공하는 특수한 타입들입니다.
제네릭, 맵드 타입, 조건부 타입 등의 타입 조작 기능을 이용해 실무에서 자주 사용되는 유용한 타입을 모아 놓은 것을 이야기합니다.

Partial, Required, Readonly

Partial<T>

Partial은 객체의 모든 프로퍼티를 선택적으로 만듭니다. 즉 T의 모든 프로퍼티를 optional로 바꿔 새로운 타입을 생성합니다.
객체 타입에서 필요한 부분만 사용하거나, 일부 프로퍼티의 값만 초기화 할 때 유용하게 사용 가능합니다.

interface PostType {
  title: string
  tags: string[]
  content:string
  thumbnail:string
}

const draft: partial<PostType> = {
  title:"초안",
  content:"처음쓴 내용..",
}

Required<T>

Required는 객체의 모든 프로퍼티를 필수적으로 만듭니다. 즉 T의 optional프로퍼티를 전부 필수적으로 만드는 유틸리티 타입입니다.

const ThumbnailPost: Required<PostType> = {
  title: "redux 입문하기",
  tags: ["redux"],
  content:"리덕스 입문하는법",
  thumbnail: "https://...",
}

Pick, Omit, Record

Pick<T, K>

Pick는 T타입의 프로퍼티중 K로 지정한 프로퍼티만을 포함한 새로운 타입을 만듭니다.

interface PostType {
  title: string
  tags: string[]
  content:string
  thumbnail:string
}

const legacyPost: Pick<PostType, "title" | "content"> ={
  title: "오래된 글",
  content: "늙은 컨텐츠",
}

Omit<T, K>

Omit은 T타입의 프로퍼티 중 K로 지정한 프로퍼티를 제외한 새로운 타입을 만듭니다.

const noTitlePost: Omit<PostType, "title"> = {
  content: "",
  tags: [],
  thumbnail:"",
}

Record<K, V>

Record는 K로 지정한 프로퍼티 key들이 V로 지정한 값을 가지는 객체 타입으로 만듭니다.

type ThumbnailLegacy = { // 비효율적
  large: {
    url: string;
  };
  medium: {
    url: string;
  };
  small: {
    url: string;
  };
  watch: {
    url: string;
  }
}
//   -> 효율적으로 활용가능
type Thumbnail = Record< "large" | "medium" | "small",
                        { url: string; size: number }
                       >

Exclude, Extract, ReturnType

Exclude<T, U>

Exclude는 타입T에서 U를 제외한 나머지 타입을 반환합니다.

type except = Exclude<string | boolean, string> //except = boolean

Extract<T, U>

Extract는 타입T에서 U와 일치하는 타입만 반환합니다.

type intersect = Extract<string | boolean, boolean> // intersect = string

ReturnType

ReturnType는 함수의 T의 반환값의 타입을 추출합니다.`

function Hello() {
  return "hello"
}

function Age() {
  return 18
}

type ReturnHello = ReturnType<typeof Hello> // ReturnHello = string
type ReturnAge = ReturnType<typeof Age>     // ReturnAge = number         

Reference

0개의 댓글