Search code examples
typescriptenumsstring-literalstypechecking

How to simulate a string based enum


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.


Solution

  • Taking the answer from this old question: https://stackoverflow.com/a/35257367/105937

    With TS 1.8 or later we can do the following:

    type Fruit = "orange" | "apple" | "banana";
    
    const Fruit = {
        Orange: "orange" as Fruit,
        Apple:  "apple" as Fruit,
        Banana: "banana"  as Fruit
    };
    

    And then use it as Fruit.Orange which will be resolved to "orange".