Enum vs Union Types
👨💼 Let's compare enums with union types. Both solve similar problems, but have
different tradeoffs.
// Enum approach
enum Color {
Red = 'red',
Green = 'green',
Blue = 'blue',
}
function paintWithEnum(color: Color) {}
paintWithEnum(Color.Red) // Must use enum value
// Union type approach (inline)
function paintWithUnion(color: 'red' | 'green' | 'blue') {}
paintWithUnion('red') // Can use string directly
- Implement logging using an enum
- Implement the same feature using inline union types
- Compare the syntax and usage
💰 Inline union in function signature:
function makeRequest(method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string) {
// ...
}
makeRequest('GET', '/api/users') // Works with string literals
If you see an "experimental transform-types" warning when running this step,
that's from the workshop runtime and can be ignored.