본문 바로가기
IT/typescript

[Typescript] index signature vs mapped type

by 내일은교양왕 2024. 2. 5.

결론

mapped type 추천

 

이유

컴파일 시 에러가 발생하기 때문에 실수를 예방할 수 있음

 

type Fruite = 'Banana' | 'Apple' | 'Orange'

const PriceMap: {[fruit:string]:number} = {
    Apple: 1000,
    Banana: 1000,
    Orange: 2000,
}

const PriceMap2: {[fruit in Fruite]:number} = {
    Apple: 1000,
    Banana: 1000,
    Orange: 2000,
}

function getDiscountedPrice(fruit: string, discount: number) {
    return PriceMap[fruit] - discount
}

const a = getDiscountedPrice('Kiwi', 300)

function getDiscountedPrice2(fruit: Fruite, discount: number) {
    return PriceMap2[fruit] - discount
}

const b = getDiscountedPrice2('Kiwi', 300) // complied error

 

 

 

https://fe-developers.kakaoent.com/

 

홈 | 카카오엔터테인먼트 FE 기술블로그

 

fe-developers.kakaoent.com

 

'IT > typescript' 카테고리의 다른 글

[Typescript] asserts를 이용한 타입 가드 활용  (0) 2024.02.05
[Typescript] 외부 패키지의 타입 치환  (1) 2024.02.05
[Typescript] enum vs union  (0) 2024.02.05
TS - 5.0 New features  (0) 2023.07.01
TS - unknown vs any  (0) 2023.06.27