TypeScript严格枚举检查

TypeScript严格枚举检查,typescript,enums,Typescript,Enums,有没有办法强制严格使用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

有没有办法强制严格使用
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团队有意决定启用位标志,有关详细信息,请参阅。阅读该问题及其链接到的各种问题,我有一种明显的感觉,他们原本希望将枚举和位标志分开,但却无法找到进行突破性更改/添加标志的地方

它以您希望的方式使用字符串
枚举
而不是数字:

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'.

这太不幸了。。。在我看来,这是非常奇怪的行为。我不喜欢这个答案,但我会接受的!:)@弗里戈-是的。:-)我在上面添加了一个新的第一段,可能会很有用。