IT/typescript

[Typescript] index signature vs mapped type

내일은교양왕 2024. 2. 5. 12:01

결론

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