What is the output of the following TypeScript code when compiled to JavaScript and run?
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
console.log(typeof Colors);
console.log(Colors.Red);enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
console.log(typeof Colors);
console.log(Colors.Red);Remember that enums in TypeScript compile to objects in JavaScript.
TypeScript enums compile to JavaScript objects. So typeof Colors is "object". Accessing Colors.Red returns the string "RED".
Consider this TypeScript code snippet. What will it output when run in JavaScript?
type Status = "success" | "error" | "loading"; const status: Status = "success"; console.log(status);
type Status = "success" | "error" | "loading"; const status: Status = "success"; console.log(status);
Union types disappear after compilation and do not add runtime code.
Union types are only for compile-time checks and do not exist at runtime. The variable status holds the string "success" and logs it.
Why do TypeScript enums add extra runtime code compared to union types?
Think about what enums provide at runtime that union types do not.
Enums compile to JavaScript objects to allow runtime access to their members and support reverse mapping (for numeric enums). Union types are erased at compile time and produce no runtime code.
Given these two TypeScript declarations, what will be the size in bytes of the compiled JavaScript code for each?
enum Directions {
Up,
Down,
Left,
Right
}
type DirectionsUnion = "Up" | "Down" | "Left" | "Right";Consider what code is generated for enums vs union types.
Enums generate JavaScript objects with properties for each member, increasing code size. Union types are erased and produce no runtime code, so they add no size.
What is the output and runtime difference when running this code?
enum RegularEnum {
A = 1,
B = 2
}
const enum ConstEnum {
A = 1,
B = 2
}
console.log(RegularEnum.A);
console.log(ConstEnum.B);Recall how const enums are compiled differently than regular enums.
Regular enums compile to objects available at runtime. Const enums are inlined by the compiler and do not generate runtime objects, so their values are replaced directly in code.