Say I have a numeric enum:
const enum EStatus {
Busy = 0,
Available = 1,
Away = 2
}
TypeScript will not complain when I do the following:
const status: EStatus = 4
However if I have a string enum:
const enum EDayOfWeekend {
Saturday = "Saturday",
Sunday = "Sunday"
}
Then TypeScript will complain when I try to do the following:
const dayOfWeekend: EDayOfWeekend = "Tuesday"
I would have expected TypeScript to be consistent with either allowing both, or not allowing either. IMO it should not allow for anything other than the defined values to be used, or even better enforce that you can only use the enum itself to initialise variables, e.g.
const dayOfWeekend = EDayOfWeekend.Saturday
I'd be interested to know why this inconsistency exists within TypeScript and whether it is there by design.
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. In this GhitHub issue Daniel Rosenwasser makes the compiler team's reasoning clear:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With