Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Type design: unions, newtypes & generics

Using the type system to rule out bugs: models in which invalid states cannot be built, newtypes for IDs and units, checks that every case is handled, states encoded as types, constrained generics, variance and higher-kinded types. It goes deeper than the Types & syntax entries, which show how to read generics and tagged variants, and the Paradigms entries, which introduce algebraic data types.

Make illegal states unrepresentable: unions over flags, parse don't validate, smart constructors

TypeScript

Name alternatives and tagged variants (Types & syntax) shows how to write a union; this entry uses unions and validated constructors to design a model in which nonsense combinations cannot be built. Optional fields and boolean flags allow combinations that mean nothing, such as a contact with neither an email nor a phone, or verified: true with no date. Replace each such group with a union that lists only the valid shapes (Reach in the example). Wrap values that need checking in a class with a private constructor and a static parse, so every Email in the program has passed it. "Parse, don't validate" means doing this once at the boundary: loose input goes in, and a typed Contact or an error comes out, so later code never checks again.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Before: two optionals allow a contact with neither an email nor a phone.
type LooseContact = { name: string; email?: string; phone?: string };

// A smart constructor: the constructor is private, so parse is the only way to get an Email.
class Email {
  readonly #value: string;
  private constructor(value: string) {
    this.#value = value;
  }
  static parse(raw: string): Email | Error {
    const value = raw.trim().toLowerCase();
    return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value) ? new Email(value) : new Error(`bad email: ${raw}`);
  }
  toString(): string {
    return this.#value;
  }
}
// new Email('x');
//   error: Constructor of class 'Email' is private and only accessible within the class declaration.

// After: a union lists only the valid shapes of "at least one of email and phone".
type Reach =
  | { kind: 'email'; email: Email }
  | { kind: 'phone'; phone: string }
  | { kind: 'both'; email: Email; phone: string };
type Contact = { name: string; reach: Reach };

// Parse, don't validate: loose input goes in once, a Contact or an error comes out,
// and code that receives a Contact never checks it again.
function parseContact({ name, email: rawEmail, phone }: LooseContact): Contact | Error {
  const email = rawEmail === undefined ? undefined : Email.parse(rawEmail);
  if (email instanceof Error) return email;
  if (email && phone) return { name, reach: { kind: 'both', email, phone } };
  if (email) return { name, reach: { kind: 'email', email } };
  if (phone) return { name, reach: { kind: 'phone', phone } };
  return new Error('need an email or a phone');
}

function sendTo(c: Contact): string {
  switch (c.reach.kind) {
    case 'email':
    case 'both':
      return `mail ${c.reach.email}`; // email is guaranteed valid here
    case 'phone':
      return `text ${c.reach.phone}`;
  }
}

const ana = parseContact({ name: 'Ana', email: ' Ana@Example.com ' });
const lee = parseContact({ name: 'Lee', phone: '+15550100' });
assert(!(ana instanceof Error) && !(lee instanceof Error));
assert(parseContact({ name: 'Nobody' }) instanceof Error);
assert(parseContact({ name: 'Bad', email: 'nope' }) instanceof Error);
console.log(sendTo(ana), '|', sendTo(lee));

In practice: when you write a comment such as "set only when X", make it a union variant instead. Keep the loose type only for input, parse it at the edge (an API handler, a form), and pass the precise type everywhere else.

private on a constructor is compile-time only; #value is a real JavaScript private field, so the value cannot be read or forged from outside at run time either.

A branded string with a parse function is a lighter alternative to a class when instances need no methods.

For input schemas, Zod 4 (zod 4.6.7) parses unknown data into such types; z.discriminatedUnion builds the unions.

Wrap a primitive in a distinct type: brands, defined types, tuple structs, strong typedefs

TypeScript

Where Name alternatives and tagged variants (Types & syntax) names a set of values, a newtype gives one kind of value its own type, so two values with the same representation (two string IDs, meters and feet) cannot be swapped. TypeScript compares types by structure, so two aliases of string are interchangeable and a UserId can be passed where an OrderId is expected. A branded type adds a property that exists only in the type: `string & { readonly __brand: 'UserId' }`. Plain strings and other brands no longer fit, while the value stays an ordinary string at run time with no wrapper and no cost.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// A brand is a phantom property: it exists only in the type, never at run time.
type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };
type Cents = number & { readonly __brand: 'Cents' };

// Constructor functions are the only place a cast to the brand happens.
function userId(raw: string): UserId {
  if (!/^u_[a-z0-9]+$/.test(raw)) throw new Error(`not a user id: ${raw}`);
  return raw as UserId;
}
function orderId(raw: string): OrderId {
  if (!raw.startsWith('o_')) throw new Error(`not an order id: ${raw}`);
  return raw as OrderId;
}
function cents(n: number): Cents {
  if (!Number.isInteger(n)) throw new Error(`cents must be whole: ${n}`);
  return n as Cents;
}

// Arithmetic on a brand returns plain number, so re-brand the result.
const addCents = (a: Cents, b: Cents): Cents => cents(a + b);

function cancelOrder(user: UserId, order: OrderId): string {
  return `${user} cancelled ${order}`;
}

const u = userId('u_42');
const o = orderId('o_9001');
console.log(cancelOrder(u, o));
// cancelOrder(o, u);
//   error: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'.
// cancelOrder('u_42', o);
//   error: Argument of type 'string' is not assignable to parameter of type 'UserId'.

// A brand is still a string, so reading it needs no unwrapping.
assert.equal(u.toUpperCase(), 'U_42');
assert.equal(addCents(cents(250), cents(199)), 449);
assert.throws(() => userId('42'));
console.log('total', addCents(cents(250), cents(199)));

In practice: brand IDs, units and validated strings that are easy to mix up. Create branded values only in small constructor functions that check the input and do the single `as` cast; everything else receives the brand from them. Arithmetic on a branded number returns plain number, so re-brand the result through the constructor.

A brand is erased: typeof still says "string", and JSON.parse output is never branded until it passes a constructor.

Using `declare const brand: unique symbol` as the key instead of __brand hides the property from autocompletion and from other modules.

Zod 4 (zod 4.6.7) has .brand<'UserId'>() to produce branded types from a schema; Effect (effect 4.1.2) has Brand.

Make the compiler check every case: assertNever, exhaustive linters, match, std::visit

TypeScript

Algebraic data types (in Paradigms) shows how to define a discriminated union; this entry covers the checks that turn a forgotten case into a compile error. After the last case of a switch on the tag, the value has type never. Passing it to a function that accepts only never (assertNever) rejects a missing case at compile time, and the throw inside catches bad data at run time. `value satisfies never` (TS 4.9+) does the same check with no helper and no runtime code, and `satisfies Record<Union['kind'], V>` checks that a lookup table has a key for every tag. The typescript-eslint rule switch-exhaustiveness-check reports switches over a union that miss a case.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

type Notice =
  | { channel: 'email'; address: string }
  | { channel: 'sms'; phone: string }
  | { channel: 'push'; deviceId: string };

function assertNever(value: never): never {
  throw new Error(`unhandled notice: ${JSON.stringify(value)}`);
}

// 1. A switch on the discriminant, with never in the default.
function target(n: Notice): string {
  switch (n.channel) {
    case 'email':
      return n.address;
    case 'sms':
      return n.phone;
    case 'push':
      return n.deviceId;
    default:
      // Adding { channel: 'slack' } to Notice makes this line fail:
      // Argument of type '{ channel: "slack"; ... }' is not assignable to parameter of type 'never'.
      return assertNever(n);
  }
}

// 2. A switch used only for side effects: 'satisfies never' checks without a helper.
function log(n: Notice, lines: string[]): void {
  switch (n.channel) {
    case 'email':
    case 'sms':
      lines.push(`text to ${target(n)}`);
      break;
    case 'push':
      lines.push(`push to ${n.deviceId}`);
      break;
    default:
      n satisfies never; // compile-time only: emits nothing
  }
}

// 3. A lookup table: satisfies Record<...> rejects a missing or misspelled key,
// while the object keeps its own literal type.
const costCents = {
  email: 0,
  sms: 4,
  push: 0
} satisfies Record<Notice['channel'], number>;
// Removing push gives: Property 'push' is missing in type '{ email: number; sms: number; }'.

const notices: Notice[] = [
  { channel: 'email', address: 'ana@example.com' },
  { channel: 'sms', phone: '+15550100' },
  { channel: 'push', deviceId: 'dev-7' }
];
const lines: string[] = [];
for (const n of notices) log(n, lines);
const total = notices.reduce((sum, n) => sum + costCents[n.channel], 0);

assert.deepEqual(lines, ['text to ana@example.com', 'text to +15550100', 'push to dev-7']);
assert.equal(total, 4);
console.log(lines.join('\n'));
console.log('total cost', total);

In practice: end every switch over a union with an assertNever default. Prefer a lookup table checked with satisfies when each case maps to a value. Keep this check in code that must change when a variant is added, and do not paper over it with a plain default branch.

A default branch that returns a fallback value switches the check off: the new variant silently takes the fallback.

Without a default, a function with a declared return type also catches a missing case (error TS2366: Function lacks ending return statement), but a switch used only for side effects compiles silently; assertNever covers both.

The check is compile-time only. JSON from outside can still carry an unknown tag, which is why assertNever throws instead of returning.

@typescript-eslint/switch-exhaustiveness-check (typescript-eslint 8) needs type information; it also catches switches used only for side effects when you prefer a lint rule to a helper.

Allow a call only in the right state (typestate): state types, consuming self, PhantomData, tag templates

TypeScript

Name alternatives and tagged variants (Types & syntax) puts every state in one union; typestate gives each state its own type, so a call that is wrong for the current state does not compile. In TypeScript each state is an object type with a status literal, and each transition is a function that accepts exactly one state and returns the next: submit(Draft): InReview, approve(InReview): Published. Calling url on a post in review is a compile error. The union of all states (Post) is still useful for stored data: switching on status narrows to the state and its allowed operations.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Each state is its own type; the status literal tells them apart at run time too.
type Draft = { readonly status: 'draft'; readonly title: string; readonly body: string };
type InReview = {
  readonly status: 'in-review';
  readonly title: string;
  readonly body: string;
  readonly reviewer: string;
};
type Published = {
  readonly status: 'published';
  readonly title: string;
  readonly body: string;
  readonly publishedAt: Date;
};
type Post = Draft | InReview | Published;

// Transitions accept only the state they start from and return the next one.
const draft = (title: string): Draft => ({ status: 'draft', title, body: '' });
const edit = (d: Draft, body: string): Draft => ({ ...d, body });
function submit(d: Draft, reviewer: string): InReview {
  if (d.body.length === 0) throw new Error('empty post');
  return { ...d, status: 'in-review', reviewer };
}
const reject = (r: InReview): Draft => ({ status: 'draft', title: r.title, body: r.body });
const approve = (r: InReview, at: Date): Published => ({
  status: 'published',
  title: r.title,
  body: r.body,
  publishedAt: at
});

// Only a published post has a URL.
const url = (p: Published): string => `/posts/${p.title.toLowerCase().replaceAll(' ', '-')}`;

let d = edit(draft('Type State'), 'States as types.');
const review = submit(d, 'lee');
// url(review);
//   tsc 6: Argument of type 'InReview' is not assignable to parameter of type 'Published'.
//   tsc 7: Property 'publishedAt' is missing in type 'InReview' but required in type 'Published'.
// approve(d, new Date());
//   tsc 6: Argument of type 'Draft' is not assignable to parameter of type 'InReview'.
//   tsc 7: Property 'reviewer' is missing in type 'Draft' but required in type 'InReview'.
d = reject(review);
const live = approve(submit(edit(d, 'States as types, revised.'), 'lee'), new Date(0));
assert.equal(url(live), '/posts/type-state');

// Data loaded from storage is a Post; narrowing on status picks the allowed operations.
function describe(p: Post): string {
  switch (p.status) {
    case 'draft':
      return `draft (${p.body.length} chars)`;
    case 'in-review':
      return `waiting for ${p.reviewer}`;
    case 'published':
      return `live at ${url(p)}`;
  }
}
for (const p of [d, review, live] satisfies Post[]) console.log(describe(p));

In practice: use it when the order of steps matters (draft, review, publish; open, authenticate, query) and wrong calls are costly. Keep the state objects immutable so an old state cannot be changed behind your back.

TypeScript cannot stop reuse of an old state value: after submit(d), d is still a Draft. Rebinding variables (let d = ...) or keeping states in a store helps.

Structural typing means two states with the same fields are interchangeable; the status literal is what keeps them apart.

Constrain a generic type: extends + keyof, type sets, trait bounds, concepts

TypeScript

Read a type parameter (Types & syntax) shows how to read <T> in a signature; this entry covers writing the constraint that says what T must support. `T extends X` limits a type parameter to types assignable to X, so the body may use X's members while the caller keeps its full type (byId returns Map<string, User>, not Map<string, { id: string }>). `K extends keyof T` ties one parameter to another's keys, and T[K] is the matching property type. A const type parameter (TS 5.0+) infers literal types, and a default (T = string) applies when nothing else decides T.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// extends: T must have at least these members; the caller's full type is kept.
function byId<T extends { id: string }>(items: readonly T[]): Map<string, T> {
  return new Map(items.map((item) => [item.id, item]));
}

// keyof: K must be one of T's keys, and T[K] is that property's type.
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

// A type built from T constrains the other argument: the patch may only use T's keys.
function update<T extends object>(value: T, patch: Partial<T>): T {
  return { ...value, ...patch };
}

// A const type parameter (TS 5.0+) infers literal types without `as const` at the call.
function firstOf<const T extends readonly unknown[]>(items: T): T[0] {
  return items[0];
}

// A default type argument, used when the caller gives none and inference has nothing to go on.
type Page<T = string> = { items: T[]; next?: string };

type User = { id: string; name: string; age: number };
const users: User[] = [
  { id: 'u1', name: 'Ana', age: 31 },
  { id: 'u2', name: 'Lee', age: 27 }
];

const index = byId(users);
assert.equal(index.get('u2')?.name, 'Lee'); // T was inferred as User, not { id: string }
const ages: number[] = pluck(users, 'age');
// pluck(users, 'email');
//   error: Argument of type '"email"' is not assignable to parameter of type 'keyof User'.
// byId([{ name: 'no id' }]);
//   error: Object literal may only specify known properties, and 'name' does not exist in type '{ id: string; }'.
// byId([{ id: 'x', extra: 1 }]) compiles: the extra property becomes part of T.
const older = update(users[0], { age: 32 });
// update(users[0], { email: 'x' });
//   error: Object literal may only specify known properties, and 'email' does not exist in type 'Partial<User>'.
const mode = firstOf(['fast', 'safe']); // type 'fast', not string
const page: Page = { items: ['a', 'b'] };

console.log(ages, older.age, mode, page.items.length);

In practice: constrain only what the body uses. Prefer a constraint over typing the parameter as the constraint itself when the caller needs its exact type back. Constraints are compile-time only; validate outside data separately.

Extra properties pass a constraint: byId([{ id: 'x', extra: 1 }]) compiles, because T is inferred as { id: string; extra: number }. Only a missing or mistyped id is an error. The excess-property check applies where the parameter type is fixed, as with Partial<T> in update.

T extends string accepts literal types such as "a" too; inside the function T may be narrower than string.

Know when subtypes substitute (variance): covariant arrays, invariant slices, lifetime subtyping, covariant returns

TypeScript

Read a type parameter (Types & syntax) treats each instantiation on its own; variance is the rule for when a container of Dog can be used where a container of Animal is expected. If Dog is a subtype of Animal, a producer of Dogs can stand in for a producer of Animals (covariant), and a consumer of Animals can stand in for a consumer of Dogs (contravariant). TypeScript treats mutable arrays as covariant, which is unsound: an Animal[] alias of a Dog[] can push a Cat. Function-type parameters are checked contravariantly under strictFunctionTypes (part of --strict), but parameters of methods written with method syntax stay bivariant, so a Vet that only treats Dogs can be assigned to one that treats any Animal. Since TS 4.7, `out T` and `in T` on a type parameter state the intended variance and are checked.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

type Animal = { name: string };
type Dog = Animal & { bark(): string };
type Cat = Animal & { meow(): string };

const rex: Dog = { name: 'Rex', bark: () => 'woof' };
const tom: Cat = { name: 'Tom', meow: () => 'meow' };

// 1. Mutable arrays are covariant, which is unsound: this compiles.
const dogs: Dog[] = [rex];
const animals: Animal[] = dogs; // allowed: Dog[] is treated as a subtype of Animal[]
animals.push(tom); // now dogs holds a cat
assert.throws(() => dogs.map((d) => d.bark())); // TypeError at run time

// readonly arrays are safe to treat covariantly because nothing can be pushed.
const view: readonly Animal[] = [rex];
// view.push(tom);  error: Property 'push' does not exist on type 'readonly Animal[]'.
assert.equal(view.length, 1);

// 2. Function parameters are contravariant under strictFunctionTypes (part of --strict).
type AnimalHandler = (a: Animal) => string;
type DogHandler = (d: Dog) => string;
const greet: AnimalHandler = (a) => `hi ${a.name}`;
const forDogs: DogHandler = greet; // fine: a handler of any animal can handle a dog
// const wrong: AnimalHandler = (d: Dog) => d.bark();
//   error: Type '(d: Dog) => string' is not assignable to type 'AnimalHandler'.
assert.equal(forDogs(rex), 'hi Rex');

// 3. Method syntax stays bivariant, even with --strict: this compiles and crashes.
interface Vet {
  treat(a: Animal): string; // method syntax: parameters checked bivariantly
}
const dogVet: Vet = { treat: (d: Dog) => d.bark() };
assert.throws(() => dogVet.treat(tom));
// Writing it as a property, treat: (a: Animal) => string, makes the line above an error.

// 4. Explicit variance annotations (TS 4.7+) state the intent and are checked.
interface Source<out T> {
  get: () => T;
}
interface Sink<in T> {
  put: (value: T) => void; // property syntax, so the parameter is checked strictly
}
const dogSource: Source<Dog> = { get: () => rex };
const animalSource: Source<Animal> = dogSource; // out: covariant
const seen: string[] = [];
const animalSink: Sink<Animal> = { put: (a) => void seen.push(a.name) };
const dogSink: Sink<Dog> = animalSink; // in: contravariant
dogSink.put(rex);
// interface Bad<out T> { put: (value: T) => void }
//   error: Type 'Bad<sub-T>' is not assignable to type 'Bad<super-T>' as implied by variance annotation.
console.log(animalSource.get().name, seen, dogs.map((d) => d.name));

In practice: accept readonly T[] for arrays you only read, declare callback members as properties (treat: (a: Animal) => string) rather than methods so their parameters are checked strictly, and add in/out annotations on library types where the variance matters.

Method bivariance is deliberate: it keeps types like Array<T> (whose methods take T) usable covariantly. It also lets a variance annotation pass on a method that it would reject on a property.

An in/out annotation is checked against the structure, and once present it replaces structural comparison between instantiations: with interface Src<in out T> { get: () => T }, assigning a Src<Dog> to a Src<Animal> is an error (TS2322) although the structure alone would allow it. Annotate only the variance the structure already has.

Abstract over containers (higher-kinded types): HKT encodings, GATs, template template parameters

TypeScript

Read a type parameter (Types & syntax) covers parameters that stand for a type such as number; this entry covers parameters that would stand for a type constructor such as Array itself, so one function could work over any container. A kind is the type of a type. number has kind *, an ordinary type. Array on its own is a type constructor of kind * -> *: give it number and you get the type number[]. A higher-kinded type parameter would stand for a constructor, so one function could map over any container: `map<F<_>>`. TypeScript has no such parameter. Libraries encode it: an interface maps a string name to each constructor (URItoKind), Kind<F, A> looks the name up, and a Functor<F> is written against Kind. fp-ts uses this encoding; Effect uses a similar TypeLambda encoding.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

// Array and Box are type constructors: give them a type (number) and you get a type.
// TypeScript cannot take "Array" itself as a type parameter (no F<_>), so libraries
// encode it: an interface maps a name to each constructor, and Kind looks it up.
type Box<A> = { readonly value: A };

interface URItoKind<A> {
  Array: A[];
  Box: Box<A>;
}
type URIS = keyof URItoKind<unknown>;
type Kind<F extends URIS, A> = URItoKind<A>[F];

// A Functor is "a container you can map over", written once for any registered F.
interface Functor<F extends URIS> {
  map<A, B>(fa: Kind<F, A>, f: (a: A) => B): Kind<F, B>;
}

const arrayFunctor: Functor<'Array'> = { map: (fa, f) => fa.map(f) };
const boxFunctor: Functor<'Box'> = { map: (fa, f) => ({ value: f(fa.value) }) };

// Generic over the container itself, not just the element type.
function double<F extends URIS>(F: Functor<F>, fa: Kind<F, number>): Kind<F, number> {
  return F.map(fa, (n) => n * 2);
}

const xs = double(arrayFunctor, [1, 2, 3]);
const b = double(boxFunctor, { value: 21 });
assert.deepEqual(xs, [2, 4, 6]);
assert.equal(b.value, 42);
// double(boxFunctor, [1, 2]);
//   tsc 6: Argument of type 'number[]' is not assignable to parameter of type 'Box<number>'.
//   tsc 7: Property 'value' is missing in type 'number[]' but required in type 'Box<number>'.

// Without an encoding, the usual alternative is an interface over a concrete container.
interface Mappable<A> {
  map<B>(f: (a: A) => B): Mappable<B>; // returns Mappable<B>, not the original class
}
class Maybe<A> implements Mappable<A> {
  readonly #v: A | undefined;
  private constructor(v: A | undefined) {
    this.#v = v;
  }
  static of<A>(v: A): Maybe<A> {
    return new Maybe(v);
  }
  static none<A>(): Maybe<A> {
    return new Maybe<A>(undefined);
  }
  map<B>(f: (a: A) => B): Maybe<B> {
    return this.#v === undefined ? Maybe.none<B>() : Maybe.of(f(this.#v));
  }
  get(fallback: A): A {
    return this.#v ?? fallback;
  }
}
console.log(xs, b.value, Maybe.of(20).map((n) => n + 1).get(0), Maybe.none<number>().get(-1));

In practice: most application code needs no HKTs; a generic function per container, or an interface such as Mappable<A>, is enough. Reach for an encoding only when writing a library that must abstract over several container types, and expect harder error messages.

Each container must be registered in URItoKind by name; fp-ts lets other modules add entries through declaration merging.

Mappable<A>.map returns Mappable<B>, not Maybe<B>: without HKTs an interface cannot say "the same container". Maybe narrows the return type itself.

Library versions: fp-ts 2.16.11 and effect 4.1.2 (its HKT module defines TypeLambda).