TypeScript中枚举的判别属性

时间:2018-03-22 17:19:18

标签: typescript enums pattern-matching discriminated-union

让一个开关为一个判别式枚举联合工作最简单的方法是什么? 基本上我试图模仿某种模式匹配。

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

1 个答案:

答案 0 :(得分:3)

拳头,在你的情况下,枚举是基于数字的Typescript。这意味着在您的示例中Fruit.Apple as Grocery === Vegetable.Tomato as Grocery; 可以为真:)

我建议使用基于字符串的枚举并查看以下示例(但是在更复杂的情况下,枚举值并不重要,最好使用" Kind&#34创建界面;和枚举值字段):

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