Bird
Raised Fist0
Typescriptprogramming~10 mins

Enum vs union literal type trade-offs in Typescript - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Enum vs union literal type trade-offs
Define Enum
↓
Use Enum value
↓
Compile to JS object
↓
Runtime available
↓
Define Union Literal Type
↓
Use literal values
↓
No JS output
↓
Compile-time only
Shows how enums create runtime objects while union literals exist only at compile time.
Execution Sample
Typescript
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let c: Color = Color.Red;
Defines an enum Color and assigns a value from it.
Execution Table
StepActionEvaluationResult
1Define enum ColorCreate JS object with keys Red, Green, Blue{ Red: 'RED', Green: 'GREEN', Blue: 'BLUE' }
2Assign c = Color.RedLook up Color.Red'RED'
3Use c in codeValue is 'RED'c = 'RED'
4Define union type ColorUnion = 'RED' | 'GREEN' | 'BLUE'No JS outputType only
5Assign cu: ColorUnion = 'RED'Check if 'RED' is in unionValid assignment
6Use cu in codeValue is 'RED'cu = 'RED'
7EndNo more stepsExecution stops
💡 All assignments valid; union literals have no runtime object; enums do.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5After Step 6Final
cundefined'RED''RED'N/AN/A'RED'
cuundefinedN/AN/A'RED''RED''RED'
Key Moments - 3 Insights
Why does enum create a JavaScript object but union literal types do not?
Enums generate real JavaScript objects at runtime (see Step 1 in execution_table), so their values exist in the output code. Union literal types are only for compile-time checks and disappear after compilation (see Step 4).
Can you assign any string to a union literal type variable?
No, only the exact strings listed in the union are allowed (see Step 5). Assigning other strings causes a compile error.
Which is safer to use if you want to avoid runtime overhead?
Union literal types have no runtime overhead because they don't create objects (Step 4). Enums create objects which exist at runtime (Step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of variable 'c' after Step 3?
A'Green'
B'RED'
Cundefined
D'BLUE'
💡 Hint
Check the 'Result' column for Step 3 in execution_table.
At which step does the union literal type variable 'cu' get assigned a value?
AStep 2
BStep 3
CStep 5
DStep 1
💡 Hint
Look for 'Assign cu: ColorUnion = 'RED'' in execution_table.
If you want to avoid any runtime JavaScript object creation, which should you choose?
AUnion literal type
BEnum
CBoth create runtime objects
DNeither creates runtime objects
💡 Hint
See the 'Evaluation' and 'Result' columns for Steps 1 and 4 in execution_table.
Concept Snapshot
Enum vs Union Literal Types in TypeScript:
- Enum creates a runtime JS object with named values.
- Union literal types exist only at compile time, no JS output.
- Enums allow reverse mapping and runtime checks.
- Union literals are safer with zero runtime overhead.
- Choose based on need for runtime presence or pure type safety.
Full Transcript
This visual execution compares TypeScript enums and union literal types. Enums create JavaScript objects at runtime, so their values exist in the output code. Union literal types only exist during compilation and disappear after, providing type safety without runtime cost. Variables assigned enum values hold the actual string or number from the enum object. Variables with union literal types hold strings but have no runtime object backing them. This trade-off helps decide when to use enums for runtime features or union literals for lightweight type checks.

Practice

(1/5)
1. Which statement best describes a key difference between TypeScript enums and union literal types?
easy
A. Enums create runtime objects, while union literal types only exist at compile time.
B. Union literal types generate JavaScript code, enums do not.
C. Enums cannot restrict values, union literal types can.
D. Union literal types allow dynamic value assignment, enums do not.

Solution

  1. Step 1: Understand enums and union literal types

    Enums create named objects that exist in the generated JavaScript code at runtime. Union literal types only exist during TypeScript's type checking and do not produce runtime code.
  2. Step 2: Compare runtime presence

    Since union literal types are erased after compilation, they cannot be used as runtime objects, unlike enums.
  3. Final Answer:

    Enums create runtime objects, while union literal types only exist at compile time. -> Option A
  4. Quick Check:

    Runtime object presence = A [OK]
Hint: Enums exist at runtime; union types do not [OK]
Common Mistakes:
  • Thinking union types generate runtime code
  • Believing enums cannot restrict values
  • Confusing dynamic assignment capabilities
2. Which of the following is the correct syntax to define a union literal type for colors 'red', 'green', and 'blue' in TypeScript?
easy
A. enum Colors { 'red', 'green', 'blue' }
B. type Colors = 'red' | 'green' | 'blue';
C. type Colors = ['red', 'green', 'blue'];
D. enum Colors = 'red' | 'green' | 'blue';

Solution

  1. Step 1: Identify union literal type syntax

    Union literal types use the syntax: type Name = 'value1' | 'value2' | 'value3';
  2. Step 2: Check options for correct syntax

    type Colors = 'red' | 'green' | 'blue'; correctly uses the union literal type syntax. Options B and D misuse enum syntax, and C defines a tuple type, not a union.
  3. Final Answer:

    type Colors = 'red' | 'green' | 'blue'; -> Option B
  4. Quick Check:

    Union literal type syntax = A [OK]
Hint: Union types use | between quoted literals [OK]
Common Mistakes:
  • Using enum syntax for union types
  • Using array syntax instead of union
  • Assigning enum with = and union syntax mixed
3. Given the enum and union type below, what will be the output of the console.log statements?
enum StatusEnum { Active = 'active', Inactive = 'inactive' }
type StatusUnion = 'active' | 'inactive';

const enumValue = StatusEnum.Active;
const unionValue: StatusUnion = 'active';

console.log(enumValue === 'active');
console.log(unionValue === 'active');
medium
A. false false
B. true false
C. false true
D. true true

Solution

  1. Step 1: Understand enum and union values

    StatusEnum.Active is assigned the string 'active'. The unionValue is also the string 'active'.
  2. Step 2: Evaluate the console.log comparisons

    Both enumValue === 'active' and unionValue === 'active' compare string 'active' to 'active', so both are true.
  3. Final Answer:

    true true -> Option D
  4. Quick Check:

    String equality for enum and union = D [OK]
Hint: Enum string values equal union strings if assigned same literal [OK]
Common Mistakes:
  • Assuming enum values are numbers by default
  • Thinking enumValue is an object, not a string
  • Confusing enum and union value types
4. Identify the error in the following TypeScript code using enums and union types:
enum Direction {
  Up = 'UP',
  Down = 'DOWN'
}

type DirectionUnion = 'UP' | 'DOWN';

function move(dir: DirectionUnion) {
  console.log(dir);
}

move(Direction.Up);
move('LEFT');
medium
A. Calling move with Direction.Up causes a type error.
B. Enum Direction is missing a 'LEFT' value causing an error.
C. Calling move with 'LEFT' causes a type error.
D. Function move should accept enum Direction, not union type.

Solution

  1. Step 1: Check function parameter type

    Function move expects a parameter of type DirectionUnion, which allows only 'UP' or 'DOWN'.
  2. Step 2: Analyze function calls

    Calling move(Direction.Up) passes 'UP', which is valid. Calling move('LEFT') passes a string not in the union, causing a type error.
  3. Final Answer:

    Calling move with 'LEFT' causes a type error. -> Option C
  4. Quick Check:

    Invalid union argument = B [OK]
Hint: Union types restrict allowed strings strictly [OK]
Common Mistakes:
  • Assuming enum values are incompatible with union types
  • Thinking missing enum values cause errors
  • Believing function parameter types are flexible
5. You want to create a set of fixed string values representing user roles that can be checked at runtime and also provide type safety. Which approach is best and why?
// Option 1
enum UserRoleEnum { Admin = 'admin', User = 'user', Guest = 'guest' }

// Option 2
type UserRoleUnion = 'admin' | 'user' | 'guest';
hard
A. Use UserRoleEnum because it creates a runtime object for checks and type safety.
B. Use UserRoleUnion because it generates runtime code and is simpler.
C. Use UserRoleUnion because enums cannot restrict string values.
D. Use UserRoleEnum because union types cannot be used in type annotations.

Solution

  1. Step 1: Understand runtime and type safety needs

    To check values at runtime, you need an actual JavaScript object. Enums generate this object. Union types only exist at compile time and do not generate code.
  2. Step 2: Compare options for runtime checks and type safety

    UserRoleEnum provides both runtime presence and type safety. UserRoleUnion provides only type safety but no runtime object for checks.
  3. Final Answer:

    Use UserRoleEnum because it creates a runtime object for checks and type safety. -> Option A
  4. Quick Check:

    Runtime object + type safety = C [OK]
Hint: Enums create runtime objects; unions only type safety [OK]
Common Mistakes:
  • Thinking union types generate runtime code
  • Believing enums cannot restrict string values
  • Assuming union types can be used for runtime checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard