有没有办法强制严格使用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
Run Code Online (Sandbox Code Playgroud)
基本上,如果我说某个东西有一个enum类型,那么我希望 TypeScript 编译器(或 tslint)确保它被正确使用。对于当前的行为,我并不真正理解枚举的意义,因为它们没有被强制执行。我错过了什么?