타입 매핑 또는 열거형 매핑 기법이라고 불리는 이 패턴은
TypeScript에서 Record 유틸리티 타입을 사용하여 키-값 쌍의 타입 안전성을 보장하는 객체를 만드는 패턴이다.
이 패턴을 도입하게 된 배경은 다음과 같다.
type StatusTypeProps = 'A' | 'B' | 'C' | 'D' | 'E'
const getParsedStatusType = ({statusType}: StatusTypeProps) => {
if(StatusTypeProps === 'A') {
return '어쩌구'
}
if(StatusTypeProps === 'B') {
return '어쩌구'
}
if(StatusTypeProps === 'C') {
return '어쩌구'
}
if(StatusTypeProps === 'D') {
return '어쩌구'
}
if(StatusTypeProps === 'E') {
return '어쩌구'
}
return
}
위처럼 쓰레기같은 유틸함수를 만들었다.
하지만 타입 매핑 기법을 사용하면 다음과 같이 간단해진다.
type StatusTypeProps = 'A' | 'B' | 'C' | 'D' | 'E'
const statusTypeMap: Record<StatusTypeProps, string> = {
A: '어쩌구',
B: '어쩌구',
C: '어쩌구',
D: '어쩌구',
E: '어쩌구',
}
// 호출할때는 statusTypeMap[statusType]
이걸로 끝이고, Record 유틸리티 타입의 장점은 다음과 같다.
참고로 Record의 두번째 타입인 string은 객체의 value속성의 타입에 해당