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
🐨 Open and:
  1. Implement logging using an enum
  2. Implement the same feature using inline union types
  3. 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.

Please set the playground first

Loading "Enum vs Union Types"
Loading "Enum vs Union Types"

No tests here 😢 Sorry.