String Literal Types for Action Types
You'll learn how to use TypeScript's string literal types to make your action types safer and catch typos before runtime.
The Problem with Plain Strings
When you dispatch actions with type as a string, it's easy to make typos:
// In your reducer
case 'increment': return { count: state.count + 1 };
// Later, in a component
dispatch({ type: 'incremnet' }); // Oops! Typo, but TypeScript won't catch it
This silently fails—your reducer hits the default case and nothing happens.
The Solution: String Literal Types
Instead of typing action as { type: string }, define exact string values:
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset', payload: number };
Now TypeScript only allows those exact strings. Try to dispatch { type: 'incremnet' } and you'll get a compile-time error immediately.
The Magic: Autocomplete
When you type dispatch({ type: ' in your editor, TypeScript shows you the valid options: 'increment', 'decrement', 'reset'. It's like having guardrails that guide you to the correct path.
Think of It Like a Menu
Imagine ordering at a restaurant. A plain string type is like saying "you can order anything"—you might ask for something that doesn't exist. String literal types are like a printed menu: you can only choose items that actually exist, and the waiter (TypeScript) won't let you order "spageti" when the menu says "spaghetti."
Key Takeaway: String literal types in discriminated unions turn action types into a compile-time checklist, giving you autocomplete and catching typos before your code ever runs.