Nick Dima
Nick Dima

Reputation: 1595

Discriminant property for enum in TypeScript

What would be the easiest way to have a switch working for a discriminant union of enums? Basically I'm trying to emulate some kind of pattern matching.

enum Fruit {
  Apple,
  Banana,
  Orange
}

enum Vegetable {
  Tomato,
  Carrot,
  Potato
}

type Grocery = Fruit | Vegetable;

function checkStuff(grocery: Grocery) {
  switch (grocery.kind) {
    case "Fruit":
      doStuff(grocery);
      break;
    case "Vegetable":
      doOtherStuff(grocery);
      break;
    default:
      break;
  }  
}

Upvotes: 1

Views: 904

Answers (1)

Lajos Gallay
Lajos Gallay

Reputation: 1317

Fist, in your case enums are numeric based in Typescript. That means in your example Fruit.Apple as Grocery === Vegetable.Tomato as Grocery; can be true :)

I suggest to go with string based enums and check the following example (however in more complex situations where the enum value doesn't matter you'd better create an interface with a "Kind" and enum value field):

function doFruitStuff(a: Fruit){
     //  do something with the fruit
}

function doVegetableStuff(v: Vegetable){
     // do something with the vegetable
}

enum Fruit {
Apple = 'Apple',
Banana = 'Banana',
Orange = 'Orange'
}

enum Vegetable {
Tomato = 'Tomato',
Carrot = 'Carrot',
Potato = 'Potato'
}

type Grocery = Fruit | Vegetable;

function checkStuff(grocery: Grocery) {
    switch (grocery) {
        case Fruit.Apple:
        case Fruit.Banana:
        case Fruit.Orange:
            doFruitStuff(grocery);
            break;
        case Vegetable.Tomato:
        case Vegetable.Carrot:
        case Vegetable.Potato:
            doVegetableStuff(grocery);
            break;
        default:
            break;
    }  
}

Upvotes: 3

Related Questions