mapped type

Tags
type
부가 설명
array.map() 떠올리면 됨. 기존 형태에서 조금만 수정해서 새로운 타입을 만들 때 유용 in 키워드가 특히 유용하다 타입에서 for … in 처럼 활용 할 수 있다.
비고

mapped type

 

타입 상에서 반복문이 필요할 때 for … in 느낌으로 in 키워드 활용하기

type UserProfileUpdate = { [p in 'username' | 'email' | 'profilePhotoUrl']?: UserProfile[p] }
type UserProfileUpdate = { [p in keyof UserProfile]?: UserProfile[p] }
 
type ApiParamsType = { [O in Organizations]: { [서비스명 in 기관별_서비스_타입[O]]: Object; }; };
type 서비스Type<O extends Organizations> = { [Organization in O]: { [서비스명 in 기관별_서비스_타입[O]]: { apiName: string; endpoint: string; etcParams: Omit< 서비스Params[Organization][서비스명], keyof SimpleAuthBaseParams >; 서비스명: 서비스명; }; }; };

만들어져있는 특정 타입을 기반으로 새로운 타입을 만들고 싶을 때

상황예시

특정 타입에서 readonly만 붙인다거나, 옵셔널(?)로 만든다거나 하는 상황일 때
  • 똑같은 형태에서 옵션만 바뀐 경우인데 불필요하게 비슷한 코드를 계속 적어야함.
  • 프로퍼티 요소가 추가될 때도 번거로워짐.
type Account = { id: string; name: string; age: number; } type OptionalAccount = { id?: string; name?: string; age?: number; } type LockedAccount = { readonly id: string; readonly name: string; readonly age: number; }

코드예시

  • -로 prefix 옵션을 제거할 수도 있다. ( -readonly )
💡
in 키워드는 정말 유용하게 잘 쓰인다! 타입에서 반복문이 필요하다 싶을 때 for … in 느낌으로 사용하면 된다.
// Mapped Types 정의 type Optional<T> = { [P in keyof T]?: T[P]; // for...in }; type ReadOnly<T> = { readonly [P in keyof T]: T[P]; }; type RemoveReadOnly<T> = { -readonly [P in keyof T]: T[P]; };
// 기본 타입 정의 type Video = { title: string; author: string; }; type Animal = { name: string; age: number; }; type House = { name: string; address: string; postal: number; } // Readonly 추가된 타입 생성 type LockedVedio = ReadOnly<Video>; type LockedAnimal = ReadOnly<Animal>; type LockedHouse = ReadOnly<House>; // Optional 적용된 타입 생성 type OptionalVideo = Optional<Video>; type OptionalAnimal = Optional<Animal>; type OptionalHouse = Optional<House>;