TypeScript Utility Types and Recipes

Built-in utility types and practical application patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Common Utility Type Recipes
Use `NonNullable<T>`
type MaybeUser = { id: string } | null | undefined;
type User = NonNullable<MaybeUser>;

# Remove `null` and `undefined` from a type.

Use `Extract<T, U>`
type Shape = "circle" | "square" | 42;
type StringShape = Extract<Shape, string>;

# Keep only members assignable to another type.

Use `Exclude<T, U>`
type Shape = "circle" | "square" | 42;
type NumericFree = Exclude<Shape, number>;

# Remove members assignable to another type.

Use `Parameters<T>`
type Fn = (id: string, active: boolean) => void;
type FnArgs = Parameters<Fn>; // [id: string, active: boolean]

# Extract a function’s parameter tuple.

Use `InstanceType<T>`
class UserService {}
type UserServiceInstance = InstanceType<typeof UserService>;

# Get the instance type from a class constructor.

## API and Domain Modeling Recipes
Paginated API response type
type Paginated<T> = {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
};

# Model paginated collections with generics.

Form field error map
type FieldErrors<T> = Partial<Record<keyof T, string>>;

# Type validation errors by field name.

State machine union
type AsyncState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: string };

# Represent async UI states safely.

Typed event map
type Events = {
  "user.created": { id: string };
  "user.deleted": { id: string };
};

# Model event payloads by event name.

Recommended next

No recommendations yet.