All Resources
Reference
TypeScriptType System
June 7, 2024

TypeScript Utility Types

Master TypeScript's built-in utility types for advanced type manipulation.

Overview

TypeScript provides powerful built-in utility types for transforming and manipulating types. These enable powerful type-level programming patterns.

Common Utilities

  • Partial: Make all properties optional
  • Required: Make all properties required
  • Readonly: Make properties immutable
  • Record: Map property names to types
  • Pick/Omit: Select/exclude properties
  • Exclude/Extract: Set operations on unions

Essential Utilities

// Partial - all properties optional
interface User {
  id: number
  name: string
  email: string
}

type PartialUser = Partial<User>
// { id?: number; name?: string; email?: string }

// Required - all properties required
type RequiredUser = Required<PartialUser>

// Readonly - immutable properties
type ReadonlyUser = Readonly<User>

// Pick - select specific properties
type UserPreview = Pick<User, 'name' | 'email'>
// { name: string; email: string }

// Omit - exclude specific properties
type UserWithoutId = Omit<User, 'id'>
// { name: string; email: string }

Record Type

// Create object with specific keys
type Status = 'pending' | 'approved' | 'rejected'

type StatusCount = Record<Status, number>
// { pending: number; approved: number; rejected: number }

const counts: StatusCount = {
  pending: 5,
  approved: 10,
  rejected: 2
}

Union Operations

type A = 'a' | 'b' | 'c'
type B = 'b' | 'c' | 'd'

// Exclude - set difference
type OnlyInA = Exclude<A, B> // 'a'

// Extract - set intersection
type InBoth = Extract<A, B> // 'b' | 'c'

// Union - set union
type Combined = A | B // 'a' | 'b' | 'c' | 'd'

Advanced Patterns

// Conditional types
type IsString<T> = T extends string ? true : false

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

// Mapped types
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}

Master utility types to write less repetitive, more maintainable TypeScript code.

Curated by

Shyam