TypeScript 中枚举的判别 属性

Discriminant property for enum in TypeScript

让开关用于枚举的判别并集的最简单方法是什么? 基本上我正在尝试模拟某种模式匹配。

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;
  }  
}

首先,在您的例子中,枚举是基于 Typescript 的数字。这意味着在你的例子中 Fruit.Apple as Grocery === Vegetable.Tomato as Grocery; 可以是真的 :)

我建议使用基于字符串的枚举并检查以下示例(但是在枚举值无关紧要的更复杂的情况下,您最好创建一个带有 "Kind" 和枚举值字段的接口):

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;
    }  
}