Back to notes
#TypeScript#Programming#Tips

Essential TypeScript Tips

Useful TypeScript patterns and techniques for writing better code

2 min read290 words

Essential TypeScript Tips

TypeScript is a powerful tool for building scalable applications. Here are some essential tips to level up your TypeScript game.

Utility Types

TypeScript provides several built-in utility types that can help you manipulate types more effectively:

CODE
Partial<T>

Makes all properties optional:

TypeScript
1interface User { 2 id: number; 3 name: string; 4 email: string; 5} 6 7type PartialUser = Partial<User>; // All properties are optional

CODE
Pick<T, K>

Selects a subset of properties:

TypeScript
type UserPreview = Pick<User, 'id' | 'name'>;

CODE
Omit<T, K>

Excludes specific properties:

TypeScript
type UserWithoutId = Omit<User, 'id'>;

Discriminated Unions

Use discriminated unions for type-safe handling of different data types:

TypeScript
1type Result = 2 | { status: 'success'; data: string } 3 | { status: 'error'; error: Error } 4 | { status: 'loading' }; 5 6function handleResult(result: Result) { 7 if (result.status === 'success') { 8 console.log(result.data); // data is available here 9 } else if (result.status === 'error') { 10 console.log(result.error); // error is available here 11 } 12}

Const Assertions

Use

CODE
as const
to get the most specific literal types:

TypeScript
1const colors = ['red', 'green', 'blue'] as const; 2// Type is readonly ['red', 'green', 'blue'] 3 4const config = { 5 apiUrl: 'https://api.example.com', 6 timeout: 5000 7} as const; 8// Types are inferred as readonly literals

Generics with Constraints

Add constraints to make generics more powerful:

TypeScript
1interface HasLength { 2 length: number; 3} 4 5function getLength<T extends HasLength>(item: T): number { 6 return item.length; 7} 8 9getLength('hello'); // OK 10getLength([1, 2, 3]); // OK 11getLength(42); // Error!

Key Takeaways

  • Use utility types to reduce boilerplate
  • Leverage discriminated unions for type safety
  • Use const assertions for literal types
  • Apply generic constraints for better type checking

Happy coding! 🚀