TypeScript - Mapped Types

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; */

좋은 웹페이지 즐겨찾기