Enum

真的要使用 enum 嗎 ?

enum Fruits {
    Apple = 'APPLE',
    Pomegranate = 'POMEGRANATE',
    Persimmon = 'PERSIMMON'
}
 
const onFruitChanged = (value: Fruits): void => { 
    const fruit = Fruits[value];
    console.log(fruit);
}

這邊會得到錯誤

image 29.png

這時候我通常都會使用 as 解決,但是如果只是要一個不變的清單或許有更好的方式

const fruits = ['APPLE', 'POMEGRANATE', 'PERSIMMON'] as const;
type Fruits = typeof fruits[number];
 
const onFruitChanged = (value: string): void => { 
    const fruit: string | undefined = fruits.find(fruit => fruit === value);
 
    console.log(fruit);
}

這樣可以確保 fruits 不變且不用透過 Object.values 取值,又可以靈活的使用 type Fruits

type hint 也是沒有問題

image 30.png