Enums and union literal types both let you define a set of fixed values. They help keep your code clear and safe by limiting what values a variable can have.
When you want a group of named constants that are easy to read and use.
When you need to restrict a variable to a few specific string or number values.
When you want better autocompletion and error checking in your code editor.
When you want to use values that can be checked at compile time without extra code.
When you want to keep your code simple and avoid extra generated code.
Syntax
Typescript
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
// vs
type Color = "RED" | "GREEN" | "BLUE";
Enum creates a named object with values you can use.
Union literal type defines a type that can only be one of the listed values.
Examples
Enum with numbers starting at 1. Values auto-increment.
Typescript
enum Direction {
Up = 1,
Down,
Left,
Right
}
Union literal type with string values.
Typescript
type Direction = "Up" | "Down" | "Left" | "Right";
Enum with string values and usage example.
Typescript
enum Status {
Success = "SUCCESS",
Failure = "FAILURE"
}
const s: Status = Status.Success;
Union literal type with usage example.
Typescript
type Status = "SUCCESS" | "FAILURE";
const s: Status = "SUCCESS";
Sample Program
This program shows how to use both enum and union literal type to restrict values and print them.
Typescript
enum Fruit {
Apple = "APPLE",
Banana = "BANANA",
Cherry = "CHERRY"
}
function printFruit(fruit: Fruit) {
console.log(`You chose: ${fruit}`);
}
printFruit(Fruit.Banana);
// Using union literal type
type FruitType = "APPLE" | "BANANA" | "CHERRY";
function printFruitType(fruit: FruitType) {
console.log(`You chose: ${fruit}`);
}
printFruitType("CHERRY");
OutputSuccess
Important Notes
Enums generate extra JavaScript code, union types do not.
Union literal types are simpler and often preferred for string sets.
Enums can be easier to use when you want named constants grouped together.
Summary
Enums create named objects with fixed values and generate code.
Union literal types restrict values without extra code and are simpler.
Choose based on whether you want runtime objects (enum) or just type safety (union).
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
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.
Step 2: Compare runtime presence
Since union literal types are erased after compilation, they cannot be used as runtime objects, unlike enums.
Final Answer:
Enums create runtime objects, while union literal types only exist at compile time. -> Option A
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
Step 1: Identify union literal type syntax
Union literal types use the syntax: type Name = 'value1' | 'value2' | 'value3';
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.
Final Answer:
type Colors = 'red' | 'green' | 'blue'; -> Option B
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?
StatusEnum.Active is assigned the string 'active'. The unionValue is also the string 'active'.
Step 2: Evaluate the console.log comparisons
Both enumValue === 'active' and unionValue === 'active' compare string 'active' to 'active', so both are true.
Final Answer:
true true -> Option D
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
Step 1: Check function parameter type
Function move expects a parameter of type DirectionUnion, which allows only 'UP' or 'DOWN'.
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.
Final Answer:
Calling move with 'LEFT' causes a type error. -> Option C
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?
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
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.
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.
Final Answer:
Use UserRoleEnum because it creates a runtime object for checks and type safety. -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.