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

Reusable helpers for app code and API modeling.

Use `NonNullable<T>`

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

typescriptANYtypescriptutility-typesnonnullable
typescript
type MaybeUser = { id: string } | null | undefined;
type User = NonNullable<MaybeUser>;

Useful after validation or guard logic has removed nullable cases.

Use `Extract<T, U>`

Keep only members assignable to another type.

typescriptANYtypescriptutility-typesextract
typescript
type Shape = "circle" | "square" | 42;
type StringShape = Extract<Shape, string>;

Helpful when refining broad unions into a specific subset.

Use `Exclude<T, U>`

Remove members assignable to another type.

typescriptANYtypescriptutility-typesexclude
typescript
type Shape = "circle" | "square" | 42;
type NumericFree = Exclude<Shape, number>;

`Exclude` is the inverse of `Extract` and useful for filtering unions.

Use `Parameters<T>`

Extract a function’s parameter tuple.

typescriptANYtypescriptutility-typesparameters
typescript
type Fn = (id: string, active: boolean) => void;
type FnArgs = Parameters<Fn>; // [id: string, active: boolean]

Great for wrappers, event helpers, and higher-order functions.

Use `InstanceType<T>`

Get the instance type from a class constructor.

typescriptANYtypescriptutility-typesinstancetype
typescript
class UserService {}
type UserServiceInstance = InstanceType<typeof UserService>;

Useful in dependency injection helpers or factory utilities.

API and Domain Modeling Recipes

Patterns for strongly typed forms, APIs, and state machines.

Paginated API response type

Model paginated collections with generics.

typescriptANYtypescriptapigenerics
typescript
type Paginated<T> = {
  items: T[];
  total: number;
  page: number;
  pageSize: number;
};

A generic wrapper keeps API contracts DRY across entities.

Form field error map

Type validation errors by field name.

typescriptANYtypescriptformsrecordpartial
typescript
type FieldErrors<T> = Partial<Record<keyof T, string>>;

This pattern works well for forms, settings pages, and API validation results.

State machine union

Represent async UI states safely.

typescriptANYtypescriptstate-machinesunions
typescript
type AsyncState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: string };

Discriminated unions make UI rendering branches easier to reason about.

Typed event map

Model event payloads by event name.

typescriptANYtypescripteventsmaps
typescript
type Events = {
  "user.created": { id: string };
  "user.deleted": { id: string };
};

A typed event map pairs well with `keyof` and indexed access helpers.

Recommended next

No recommendations yet.