12 cookbook

Patterns I actually reach for

Table of Contents

Branded types

type Brand<T, B extends string> = T & { readonly __brand: B };
type PortNumber = Brand<number, "PortNumber">;

function toPort(value: number): PortNumber | null {
  return value > 0 && value < 65536 ? (value as PortNumber) : null;
}

A plain number can be a port, a price, or an offset A branded type stops you passing the wrong one into a function The brand is a type only , it adds no runtime field

The cast inside toPort is the boundary Validate once, trust the branded value after

Result type

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

A discriminated union for operations that can fail ok is the discriminant The caller must handle both branches

Safe fetch

async function safeFetch<T>(url: string): Promise<Result<T, string>> {
  try {
    const response = await fetch(url);
    if (!response.ok) return { ok: false, error: String(response.status) };
    return { ok: true, value: (await response.json()) as T };
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : "unknown" };
  }
}

response.json() returns any from the DOM typings The cast to T is a claim, not a verification For untrusted input, validate the shape with a runtime parser before trusting it

No network requests were made while verifying this chapter The types were checked, the behavior needs a lab with a controlled endpoint

Posted