← All posts
TypeScriptTypeScriptPatternsDX
TypeScript Patterns I Wish I Knew Earlier
From discriminated unions to template literal types — features that changed how I write code.
## Discriminated Unions
Model state machines cleanly and get exhaustive type checking:
```typescript
type Result =
| { status: 'success'; data: T }
| { status: 'error'; error: string }
| { status: 'loading' };
```
## Template Literal Types
```typescript
type EventName = `on${Capitalize}`;
```
## Key Takeaways
- Use discriminated unions for state modeling
- Template literal types for string-shaped APIs
- Never use any — use unknown instead