0
0
Typescriptprogramming~5 mins

Enum vs union literal type trade-offs in Typescript - Quick Revision & Key Differences

Choose your learning style9 modes available
Recall & Review
beginner
What is a TypeScript enum?
An enum is a special TypeScript type that allows you to define a set of named constants, which can be either numeric or string values.
Click to reveal answer
beginner
What is a union literal type in TypeScript?
A union literal type is a type that can be one of several specific string or numeric literal values, written as a union of those literals.
Click to reveal answer
intermediate
Name one advantage of using enums over union literal types.
Enums provide a clear grouping of related constants and can be used both as types and values, which helps with code organization and readability.
Click to reveal answer
intermediate
What is a key trade-off when choosing union literal types instead of enums?
Union literal types are simpler and generate less JavaScript code, but they lack runtime representation and cannot be iterated over like enums.
Click to reveal answer
beginner
Why might you prefer union literal types for small sets of values?
Because union literal types are lightweight, have no runtime overhead, and provide better type safety with string literal types, making them ideal for small, fixed sets.
Click to reveal answer
Which of the following is true about TypeScript enums?
AThey only exist at compile time and generate no code.
BThey cannot have string values.
CThey generate JavaScript code and have runtime representation.
DThey are the same as union literal types.
What is a benefit of union literal types compared to enums?
AThey group constants under one object.
BThey can be iterated at runtime.
CThey allow dynamic value assignment.
DThey generate less JavaScript code.
Which is a limitation of union literal types?
AThey cannot be used as types.
BThey lack runtime representation for iteration.
CThey require explicit numeric values.
DThey have runtime overhead.
When might enums be preferred over union literal types?
AWhen you need to iterate over values at runtime.
BWhen you want zero runtime code.
CWhen you want simpler type definitions.
DWhen you want to avoid grouping constants.
Which statement about union literal types is false?
AThey generate runtime JavaScript objects.
BThey are ideal for small fixed sets of values.
CThey provide better type safety with string literals.
DThey do not support iteration at runtime.
Explain the main differences between enums and union literal types in TypeScript.
Think about runtime presence and code generation.
You got /5 concepts.
    Describe scenarios where you would choose union literal types over enums and vice versa.
    Consider runtime needs and code simplicity.
    You got /4 concepts.