0
0
Typescriptprogramming~5 mins

When enums add unnecessary runtime code in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a TypeScript enum?
An enum in TypeScript is a way to define a set of named constants. It creates an object at runtime that maps names to values and sometimes values back to names.
Click to reveal answer
intermediate
Why can enums add unnecessary runtime code?
Because enums generate JavaScript objects at runtime, they add extra code even if you only need compile-time type checking or simple constants.
Click to reveal answer
intermediate
What is a common alternative to enums to avoid runtime code?
Using union types of string or number literals combined with 'as const' objects can provide type safety without generating runtime code.
Click to reveal answer
advanced
How does a const enum differ from a regular enum in TypeScript?
A const enum is inlined at compile time and does not generate runtime code, but it requires 'preserveConstEnums' to be false and can cause issues with some tools.
Click to reveal answer
advanced
What is a downside of using const enums?
Const enums are erased during compilation, so if you use them with external JavaScript or certain build tools, it can cause errors because the enum object does not exist at runtime.
Click to reveal answer
What does a regular TypeScript enum generate in JavaScript?
AA function that returns enum values
BOnly type information, no JavaScript code
CAn object with keys and values representing the enum members
DA string literal union type
Which TypeScript feature avoids generating runtime code for enums?
Aconst enum
Binterface
Cclass
Dnamespace
What is a simple alternative to enums to get type safety without runtime code?
AUsing functions
BUnion of string literals with 'as const' object
CUsing interfaces
DUsing classes with static properties
What problem can const enums cause in some build setups?
ARuntime errors because enum objects do not exist
BSlower runtime performance
CLarger bundle size
DLack of type safety
When should you avoid using regular enums in TypeScript?
AWhen you want to use interfaces
BWhen you need runtime reflection
CWhen you want to use classes
DWhen you want to avoid extra runtime code
Explain why regular enums in TypeScript can add unnecessary runtime code and how to avoid it.
Think about what code is generated and alternatives that only exist at compile time.
You got /3 concepts.
    Describe the trade-offs between using regular enums and const enums in TypeScript.
    Consider runtime presence and compatibility.
    You got /4 concepts.