Skip to content
typescript

TypeScript - Utility Type Helpers

Powerful utility types for transforming and manipulating types

// Make all properties optional recursively
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
}

// Make specific keys required
type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>

// Exclude null and undefined
type NonNullableFields<T> = {
  [P in keyof T]: NonNullable<T[P]>
}

// Create union from object values
type ValueOf<T> = T[keyof T]

// Example usage
interface User {
  id: string
  name?: string
  email?: string
  settings?: {
    theme?: string
    notifications?: boolean
  }
}

type PartialUser = DeepPartial<User>
type UserWithEmail = RequireKeys<User, 'email'>
type NonNullableUser = NonNullableFields<User>

// Extract function return type
type AsyncReturnType<T extends (...args: any) => Promise<any>> =
  T extends (...args: any) => Promise<infer R> ? R : never