TypeScript Utility Types I Use Constantly

Updated Originally

TypeScript’s built-in utility types are incredibly useful. These are the ones I reach for most.

Partial & Required

type User = {
  id: number;
  name: string;
  email: string;
};

// All fields optional
type PartialUser = Partial<User>;

// All fields required (removes optional ?)
type RequiredUser = Required<User>;

Pick & Omit

// Only keep certain fields
type UserPreview = Pick<User, 'id' | 'name'>;

// Remove certain fields
type PublicUser = Omit<User, 'email'>;

Record

// Object with known key/value types
type StatusMap = Record<string, boolean>;

// More specific keys
type Config = Record<'dev' | 'staging' | 'prod', { url: string; debug: boolean }>;

Readonly & ReadonlyArray

// Immutable object
const config: Readonly<{ host: string }> = { host: 'localhost' };
config.host = 'other'; // Error!

// Immutable array
const ids: ReadonlyArray<number> = [1, 2, 3];
ids.push(4); // Error!

ReturnType & Parameters

function fetchUser(id: number): Promise<User> { /* ... */ }

// Extract the return type
type FetchResult = ReturnType<typeof fetchUser>; // Promise<User>

// Extract parameter types as tuple
type FetchParams = Parameters<typeof fetchUser>; // [id: number]

Extract & Exclude

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

// Intersection of union types
type AB = Extract<A, B>; // 'b' | 'c'

// Remove types from union
type NotBC = Exclude<A, 'b' | 'c'>; // 'a'

NonNullable

type MaybeUser = User | null | undefined;
type DefinitelyUser = NonNullable<MaybeUser>; // User

Awaited (TypeScript 4.5+)

type FetchedUser = Awaited<Promise<User>>; // User
type NestedPromise = Awaited<Promise<Promise<number>>>; // number

Combining Utilities

The real power comes from combining them:

type CreateUserInput = Omit<
  Required<Pick<User, 'name' | 'email'>>,
  never
>;

// Partial update type (all optional except id)
type UpdateUser = { id: number } & Partial<Omit<User, 'id'>>;