I have a value that comes from an API that could be either "orange"
, "apple"
or "banana"
.
So first I created a type as:
type Fruit = "orange" | "apple" | "banana";
So then I can type the value from the API as Fruit
;
type Fruit = "orange" | "apple" | "banana";
function getFruitFromApi(): Fruit {
// simulating random result
const fruits: Fruit[] = ["orange", "apple", "banana"];
return fruits[Math.floor(Math.random() * 3)];
}
const fruit: Fruit = getFruitFromApi();
switch (fruit) {
case "orange": break;
case "apple": break;
case "banana": break;
}
That's okay but I'd like to avoid having to type those strings manually in the switch. I'd like to have something like Fruit.Orange
, Fruit.Apple
and Fruit.Banana
. So basically like an enum but with the values matched with strings instead of numbers.