2

So I have code like below:

enum AnimalId {
  Dog = 2,
  Cat = 3
}

const animalIds: AnimalId[] = [AnimalId.Dog, 4];

Why Typescript is not showing error that id 4 is not assignable to type AnimalId[]?

0

2 Answers 2

1

The main reason for the difference in behavior is the ability to have flag number enums and use bitwise operators on them. For string enums there is no equivalent feature.

Here is the reasoning of Daniel Rosenwasser on GH :

The behavior is motivated by bitwise operations. There are times when SomeFlag.Foo | SomeFlag.Bar is intended to produce another SomeFlag. Instead you end up with number, and you don't want to have to cast back to SomeFlag`. I think if we did TypeScript over again and still had enums, we'd have made a separate construct for bit flags.

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

Comments

0

You can fix it by using strings instead of numbers:

enum AnimalId {
  Dog = "2",
  Cat = "3"
}

const animalIds: AnimalId[] = [AnimalId.Dog, 4]; // ❌ Type 'number' is not assignable to type 'AnimalId'.

TS Playground: https://www.typescriptlang.org/play?#code/KYOwrgtgBAgiCWECGAbAkgEygbwFBSgBEB7AcygF4oAiAJmoBp8oBhJAF0poGZrcBfXLgDGxEAGdOSBMnQZxALlgzUmANoBdLmriJVGAHQlSDKABYNAblxA

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.