타입스크립트/고급 타입

맵드 타입

webmaster 2022. 10. 18. 09:47
728x90

맵드 타입이란 기존에 정의되어 있는 타입을 새로운 타입으로 변환해 주는 문법을 의미한다. 마치 자바스크립트 map() API 함수를 타입에 적용한 것과 같은 효과를 가진다.

https://github.com/Microsoft/TypeScript/pull/12114

 

Mapped types by ahejlsberg · Pull Request #12114 · microsoft/TypeScript

This PR introduces Mapped Types, a new kind of object type that maps a type representing property names over a property declaration template. In combination with index types and indexed access type...

github.com

type Heroes = 'Hulk' | 'Capt' | 'Thor'
type HeroAges = { [K in Heroes]: number}

const ages: HeroAges = {
    Hulk: 33,
    Capt: 100,
    Thor: 1000,
}

//for in 반복문 코드
/*
var arr = ['a', 'b', 'c']
for (var key in arr) {
    console.log(arr[key])
}
 */
  • 기존 타입을 변경하는 APi이다.(array의 map의 생각하면 된다)
  • Heroes(string[]) 에서 HeroAges(number[])로 변환한다.
728x90

'타입스크립트 > 고급 타입' 카테고리의 다른 글

ES6 최신 문법  (0) 2022.10.22
JS에 TS 적용하기  (0) 2022.10.18
유틸리티 타입  (0) 2022.10.18