Predict the output · TypeScript
Numeric Enums at Runtime
Medium Predict the output Seen at Microsoft, Shopify
What does this print?
What does this print?
enum Color {
Red,
Green,
Blue = 10,
Purple,
}
console.log(Color.Green, Color.Purple, Color[10]);
1 11 Blue
Green Purple 10
1 4 Blue
1 11 undefined
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
1 11 Blue
Numeric enum members auto-increment from the previous value: Red = 0, Green = 1, Blue = 10, Purple = 11. Numeric enums also get a reverse mapping, so Color[10] is "Blue".
Enums are one of the few TypeScript features that emit runtime code. Many teams prefer union types ("red" | "green") or as const objects for that reason.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium
- Mutable Default Arguments · Easy