TypeScript Tips & Tricks for Better Code
TypeScript has become an essential tool in modern web development. In this post, I'll share some advanced patterns and tips that have made my code more robust and maintainable.
Utility Types
TypeScript's utility types are incredibly powerful for creating flexible and reusable type definitions.
Partial
Make all properties optional:
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = Partial<User>;
// Equivalent to: { id?: number; name?: string; email?: string; }
Pick<T, K>
Select specific properties:
type UserCredentials = Pick<User, 'email' | 'password'>;
// Only email and password properties
Advanced Patterns
Discriminated Unions
Create type-safe state machines:
type RequestState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: any }
| { status: 'error'; error: string };
function handleRequest(state: RequestState) {
switch (state.status) {
case 'idle':
return 'Ready to start';
case 'loading':
return 'Please wait...';
case 'success':
return `Data: ${state.data}`;
case 'error':
return `Error: ${state.error}`;
}
}
Best Practices
- Use strict mode: Enable all strict TypeScript options
- Prefer interfaces over types: Better for object shapes
- Use const assertions: For literal types
- Leverage generics: Create reusable components
Conclusion
TypeScript is more than just type annotations - it's a powerful tool for building better software. These patterns will help you write more maintainable and robust code.