6

Is there any way to enforce strict usage of enum? Some examples:

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

Basically, if I say that something has an enum type, then I want the TypeScript compiler (or alternatively tslint) to make sure that it is used correctly. With the current behavior I don't really understand the point of enums as they are not enforced. What am I missing?

1 Answer 1

7

It's an intentional design decison on the TypeScript team's part to enable bitflags, see this issue for more details. Reading that issue and the various ones it links to, I get the distinct sense they wish they'd separated enums and bitflags originally but can't get themselves around to the place of making the breaking change / adding a flag.

It works the way you want it to with a string enum rather than a numeric one:

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

Sign up to request clarification or add additional context in comments.

2 Comments

Well that's unfortunate... Very strange behavior, in my opinion. I don't like the answer, but I'll accept it! :)
@Frigo - Yeah. :-) I've added a new first paragraph above that may be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.