On this page
  1. Building Type-Level Utilities & Branded Types
  2. Contents
  3. Recursive DeepReadonly<T>
  4. Branded (Nominal) IDs in a Structural Type System

Building Type-Level Utilities & Branded Types

Prev: Type-Safe API Clients & Runtime Validation | Up: tutorials | Next: index
Rel: Conditional & Mapped Types, Readonly
Ref: TypeScript Handbook โ€” Type Manipulation
Tags: #public #web #typescript #tutorials #patterns


Contents


Recursive DeepReadonly<T>

type DeepReadonly<T> = T extends (...args: unknown[]) => unknown
  ? T
  : T extends readonly (infer U)[]
    ? readonly DeepReadonly<U>[]
    : T extends object
      ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
      : T;

Branded (Nominal) IDs in a Structural Type System

Prevent accidentally passing an OrderId where a UserId is expected โ€” with zero runtime overhead โ€” by intersecting a primitive with a unique phantom brand property:

declare const brand: unique symbol;
type Brand<T, Name extends string> = T & { readonly [brand]: Name };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;

const asUserId = (id: string) => id as UserId;
function loadUser(id: UserId) {
  return id;
}

const uid = asUserId("u_123");
loadUser(uid); // OK
// loadUser("o_999" as OrderId); // Compile-time error!

Linked from

Related notes