Record 타입

nearworld·2023년 1월 22일
0

typescript

목록 보기
17/28
Record<Keys, Type>

Record 타입은 타입스크립트의 유틸리티 타입 중 하나이며 특정하게 중첩된 객체 1개 이상을 가지는 객체에 대응하는 타입이다.

유틸리티 타입 Utility Types
유틸리티 타입은 타입스크립트에서 다른 타입들을 가공하여 새로운 타입을 만들어내는 타입이다.

그 객체는 아래와 같은 모습이다.

const displayList = {
  mobile: {
    width: 0, 
    height: 0
  },
  desktop: {
    width: 0,
    height: 0
  },
  laptop: {
    width: 0,
    height: 0
  }
}

객체 DisplayList는 중첩된 객체 mobile, desktop, laptop 들을 가지고 있다.
DisplayList 객체에 대응하는 타입을 만드는 방식을 생각해보면

interface DisplayList {
  mobile: {
    width: number,
    height: number
  },
  desktop: {
  	width: number,
  	height: number
  },
  laptop: {
    width: number,
    height: number
  }
}

인터페이스 뿐만 아니라 타입 별칭 type을 이용해 만들 수도 있겠다. 하지만 위 같은 방식은 Record 타입을 생각해 볼 때 하드 코딩이 될 수 있다. 예를 들어, 디스플레이 리스트에 등록된 중첩된 객체 타입들이 저것보다 훨씬 많다고 생각해보자.. 어마무시한 일일 수 있다..
Record 타입은 중첩된 객체들의 타입이 같다면 그 중첩된 객체들의 타입은 하나만 있으면 되고 그 하나를 여러 프로퍼티 key에 매핑하는 방식으로 간단하게 타입을 만들게 해준다.

interface DisplaySize { width: number, height: number }
type Display = 'mobile' | 'display' | 'laptop'

type DisplayList = Record<Display, DisplaySize>

const displayList: DisplayList = {
  mobile: {
    width: 0, 
    height: 0
  },
  desktop: {
    width: 0,
    height: 0
  },
  laptop: {
    width: 0,
    height: 0
  }
}

위 코드의 경우에는 Display 유니온 타입을 모두 다 중첩된 객체로 구현해줘야 하는 한계가 있다. 만약 mobile, display, laptop 키 중에서 선택적으로 쓰고 싶은 것만 중첩된 객체로 만들어 사용하고 싶다면 또 다른 유틸리티 타입인 Pick 타입을 사용하여 해결 할 수 있다.

interface DisplaySize { width: number, height: number }
type Display = 'mobile' | 'display' | 'laptop'

type DisplayList = Pick<Record<Display, DisplaySize>, 'desktop'>
const displayList: DisplayList = {
  desktop: {
    width: 0,
    height: 0
  },
}
profile
깃허브: https://github.com/nearworld

0개의 댓글