- 중복을 피하기위해 기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법(자바스크립트의
map()
함수를 적용한 것과 같은 효과)
// 기존 타입
{
name: string;
email: string;
}
// 새로운 타입
{
name: number;
email: number;
}
🖐🏻 문법
type Name = 'Kim' | 'Park' | 'Shin';
위와 같이 김, 박, 신을 유니온 타입으로 묶어주는 Name
이라는 타입이 있습니다. 여기서 각 이름에 몸무게까지 붙인 객체를 만들고 싶다면 아래와 같이 변환할 수 있습니다.
type PersonProfiles = { [T in Name] : number};
const personInfo1: PersonProfiles = {
Kim: 55,
Park: 81,
Shin: 77,
}
const personInfo2: PersonProfiles = {
Kim: 64,
Park: 61,
Shin: 'no', // error: Type 'string' is not assignable to type 'number'.
}
[T in Name]
부분은 앞에서 정의한 Name
타입의 3개의 문자열을 각각 순회하여 number
타입을 값으로 가지는 객체의 키로 정의가 됩니다. 이는 아래와 같이 정의하는 것과 동일합니다.
type PersonProfiles = {
Kim: number;
Park: number;
Shin: number;
}
🖐🏻 예제
type Subset<T> = {
[K in keyof T]? : T[K];
}
interface Person{
name: string;
age: number;
}
const onlyName: Subset<Person> = {name: 'Kim'};
const onlyAge: Subset<Person> = {age: 12};
const personInfo: Subset<Person> = {name: 'Park', age:22};
const empty: Subset<Person> = {};
interface UserProfile {
email: string;
username: string;
profilePhotoUrl: string;
}
// 1
interface UserProfileUpdate{
email? : string;
username? : string;
profilePhotoUrl? : string;
}
// 2
type UserProfileUpdate = {
email? : UserProfile['email'];
username? : UserProfile['username'];
profilePhotoUrl? : UserProfile['profilePhotoUrl'];
}
// 3
type UserProfileUpdate = {
[p in 'email' | 'username' | 'profilePhotoUrl']?: UserProfile[p]
}
// 4
type UserProfileUpdate = {
[p in keyof UserProfile]?: UserProfile[p]
}
참조
https://www.typescriptlang.org/ko/docs/handbook/2/mapped-types.html
Documentation - Mapped Types
이미 존재하는 타입을 재사용해서 타입을 생성하기
www.typescriptlang.org
https://joshua1988.github.io/ts/usage/mapped-type.html
맵드 타입 | 타입스크립트 핸드북
맵드 타입(Mapped Type)이란? 맵드 타입이란 기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법을 의미합니다. 마치 자바스크립트 map() API 함수를 타입에 적용한 것과 같은 효과를 가
joshua1988.github.io
'TypeScript > TS' 카테고리의 다른 글
읽기 전용 타입 - readonly, Readonly<T> (0) | 2022.11.02 |
---|---|
Utility Types(유틸리티 타입) - Partial, Required, Pick, Omit (0) | 2022.10.29 |