【问题标题】:Discriminant property for enum in TypeScriptTypeScript 中枚举的判别属性
【发布时间】:2018-03-22 17:19:17
【问题描述】:

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

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 enums pattern-matching discriminated-union


    【解决方案1】:

    拳头,在您的情况下,枚举是基于 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;
        }  
    }
    

    【讨论】:

    • 我没有考虑过这个解决方案。但是,是的,您在更复杂的示例中是正确的,枚举中有更多的值,而我不关心它可能变得过于冗长的值。我正在考虑使用“种类”和“值”字段的接口解决方案,但我不确定使用这些类型时它的外观如何。例如。假设我们有接口 FruitInterface { kind: "Fruit"; value: Fruit } 当我必须使用它时,我将不得不做类似 var myFruit = {value: Fruit.Apple} 而不是 var myFruit = Fruit.Apple ... 对吗?它不会让我太高兴。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2020-11-17
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多