有什么方法可以强制严格使用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)确保正确使用它。就目前的行为而言,由于枚举没有被强制执行,因此我并不太了解枚举的意义。我想念什么?
答案 0 :(得分:3)
这是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'.