Advanced TypeScript: Generics and Utility Types

Generics make functions and types reusable without sacrificing type safety. Utility types transform existing types-essential for API layers and form handling.

Generic Functions

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const n = first([1, 2, 3]);      // number | undefined
const s = first(['a', 'b']);     // string | undefined

Constrained Generics

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

Utility Types

  • Partial<T> - all properties optional
  • Pick<T, K> - subset of keys
  • Omit<T, K> - exclude keys
  • Record<K, V> - keyed object type
type UpdateUserDto = Partial<Pick<User, 'name' | 'email'>>;

Conclusion

Master generics and utilities before reaching for complex conditional types. They keep DTOs, reducers, and hook return types DRY and accurate.