3 ms·
Typescript enums emit a really weird object at runtime enum CheckboxState { On; ParentOn; Off; } Becomes { [0]: “On”, “On”: 0, [1]: “Parent
by graypegg 3y ago
Typescript enums emit a really weird object at runtime
enum CheckboxState {
On;
ParentOn;
Off;
}
Becomes
{
[0]: “On”,
“On”: 0,
[1]: “ParentOn”,
“ParentOn”: 1,
[2]: “Off”,
“Off”: 2
}
So things like Object.keys give bizarre results. It’s done this way so you can use the name or the value as an index.
- eyelidlessness 3y agoTo be clear, this kind of structure is only emitted for numeric enums. String enums with explicitly declared static values are roughly equivalent to the equivalent Record<string, string> (runtime) and a corresponding type T[keyof T] (type check time). IME, most of the complaints about enums apply only to numeric ones. The major exception to that AFAIK is the fact that enum members of any type are treated as nominally typed (as in A.Foo is not assignable to B.Foo even if they resolve to the same static value). I am among the minority who consider this a good thing, but I recognize that it violates expectations and so I understand why my position isn’t widely shared.