mapped type
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
https://joshua1988.github.io/ts/usage/mapped-type.html#맵드-타입의-기본-문법
타입 상에서 반복문이 필요할 때 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>;