【问题标题】:TypeScript strict enum checkingTypeScript 严格的枚举检查
【发布时间】:2019-03-23 05:31:04
【问题描述】:

有没有办法强制严格使用enum?一些例子:

enum AnimalType {
  Cat,
  Dog,
  Lion
}

// Example 1
function doSomethingWithAnimal(animal: AnimalType) {
  switch (animal) {
    case Animal.Cat: // ...
    case Animal.Dog: // ...
    case 99: // This should be a type error
  }
}

// Example 2
someAnimal.animalType = AnimalType.Cat; // This should be fine
someAnimal.animalType = 1; // This should be a type error
someAnimal.animalType = 15; // This should be a type error

基本上,如果我说某物具有 enum 类型,那么我希望 TypeScript 编译器(或 tslint)确保它被正确使用。对于当前的行为,我并不真正理解枚举的意义,因为它们没有被强制执行。我错过了什么?

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    启用位标志是 TypeScript 团队有意设计的决定,请参阅 this issue 了解更多详细信息。阅读该问题及其链接的各种问题,我清楚地感觉到他们希望他们最初将枚举和位标志分开,但无法让自己找到进行重大更改/添加标志的地方。

    它使用 字符串 enum 而不是数字的方式按照您想要的方式工作:

    enum AnimalType {
      Cat = "Cat",
      Dog = "Dog",
      Lion = "Lion"
    }
    
    // Example 1
    function doSomethingWithAnimal(animal: AnimalType) {
      switch (animal) {
        case AnimalType.Cat: // Works
        case AnimalType.Dog: // Works
        case "99": // Error: Type '"99"' is not assignable to type 'AnimalType'. 
      }
    }
    
    // Example 2
    const someAnimal: { animalType: AnimalType } = {
      animalType: AnimalType.Dog
    };
    let str: string = "foo";
    someAnimal.animalType = AnimalType.Cat; // Works
    someAnimal.animalType = "1"; // Type '"1"' is not assignable to type 'AnimalType'.
    someAnimal.animalType = str; // Error: Type 'string' is not assignable to type 'AnimalType'.
    

    Live Example in the Playground

    【讨论】:

    • 那很不幸...在我看来,这是非常奇怪的行为。我不喜欢这个答案,但我会接受! :)
    • @Frigo - 是的。 :-) 我在上面添加了一个新的第一段,可能有用。
    猜你喜欢
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2018-10-31
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2023-03-10
    相关资源
    最近更新 更多