Mapped Type

In9_9yu·2023년 4월 23일
1

Typescript

목록 보기
1/1

1. 겪었던 문제

타입스크립트로 개발을 하던 도중, 다음 문제와 부딪혔다.

특정 함수에 의해 데이터 타입이 변화했는데, 이것도 인터페이스로 선언해야하나?

코드로 보자

interface IReviewForm{
 	control: string;
  	power: string;
  	design: string;
}

interface ITransformReview {
  control : number;
  power : number;
  design : number;
}

const transformReview = (review : IReviewForm) : ITransformReview => {
  return ...
}

물론 위와 같이 작성해주면 문제는 없다. 하지만 mapped type을 이용하면 더 세련된 방식으로 타입을 정의할 수 있다.

interface IReviewForm{
 	control: string;
  	power: string;
  	design: string;
}

type TransformNumber<T> = {
 [K in keyof T]: number; 
}

const transformReview = (review : IReviewForm) : TransformNumber<IReviewForm> => {
  return ...
}

2. 궁금했던 점들

1. keyof T

해당 문법을 사용하면, T가 가지고 있는 key값을 모아 유니온 타입으로 만들 수 있다.

type P = {
  name:string;
  age: number;
  hobby:string;
}
type Union= keyof P; // name | age | hobby

2. typeof T

객체 데이터를 객체 타입으로 변환해주는 연산자

const person = {
  name:'Kim',
  age: 10,
  hobby: 'badminton'
}

type Person = typeof person; 
//{name: string; age : number; hobby: string;}

Q. 만약 person을 as const로 설정하면 어떻게 될까?

A. 할당 불가능 할 뿐 아니라, Type narrowing의 효과도 발생한다.

const person = {
  name:'Kim',
  age: 10,
  hobby: 'badminton'
} as const;

type Person = typeof person;
// {name:'Kim; age:10; hobby:'badminton';}

const otherPerson: Person = {
	name:'Park',
  	age: 50,
  	hobby:'baseball'
}
//Error!
// Park은 Kim에 할당할 수 없습니다.
// 50은 10에 할당할 수 없습니다.
// ... 

3. 공식문서에 소개된 내용

1. Mapping Modifiers

  • readonly
    해당 property를 readonly로 설정합니다.

  • ?
    해당 property를 optional하게 설정합니다.

  • -
    해당 property를 제거합니다.

  • +
    아무 접두사가 붙지 않으면 기본적으로 +가 붙습니다.

profile
FE 임니다

0개의 댓글