Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number enum in TypeScript allows any number whereas string enum does not

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.

like image 794
Mark Avatar asked Nov 27 '18 09:11

Mark


1 Answers

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.

like image 70
Titian Cernicova-Dragomir Avatar answered Oct 21 '22 14:10

Titian Cernicova-Dragomir