TypeScript - Mapped Types

CH_Hwang·2022년 3월 17일
0

TypeScript

목록 보기
7/12
type OnlyBoolsAndHorses = {
  [key: string]: boolean | Horse;
};
 
const conforms: OnlyBoolsAndHorses = {
  del: true,
  rodney: false,
};

optional이나 readonly와 같은 건 -+를 이용하여 수정할 수 있다.

// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};
 
type LockedAccount = {
  readonly id: string;
  readonly name: string;
};
 
type UnlockedAccount = CreateMutable<LockedAccount>;

cosole.log(typeof UnlockedAccount) // {id: string; name: stinrg}
// Removes 'optional' attributes from a type's properties
type Concrete<Type> = {
  [Property in keyof Type]-?: Type[Property];
};
 
type MaybeUser = {
  id: string;
  name?: string;
  age?: number;
};
 
type User = Concrete<MaybeUser>;

console.log(typeof User); // {id: string; name: string; age: number;}

타입스크립트 4.1 버전부터 매핑된 타입을 as를 사용하여 리매핑 할 수 있다.

type MappedTypeWithNewProperties<Type> = {
    [Properties in keyof Type as NewKeyType]: Type[Properties]
}
type Getters<Type> = {
    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
 
interface Person {
    name: string;
    age: number;
    location: string;
}
 
type LazyPerson = Getters<Person>;

console.log(tpyeof LazyPerson)  
	/*. getName: () => string;
    getAge: () => number;
    getLocation: () => string; */

0개의 댓글