Branded Types for Nominal Identity

Attach a phantom brand to primitive types so structurally identical identifiers such as UserId and OrderId cannot be mixed up.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
declare const brand: unique symbol;

export type Brand<T, B extends string> = T & { readonly [brand]: B };

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

export function asUserId(value: string): UserId {
  if (!/^usr_[a-z0-9]+$/.test(value)) throw new Error("invalid user id");
  return value as UserId;
}

export function loadUser(id: UserId): void {
  console.log("loading user", id);
}

const orderId = "ord_1" as OrderId;
// loadUser(orderId); // compile error: OrderId is not UserId

How the snippet works

Branded Types for Nominal Identity is built around the functions asUserId and loadUser.

Failure is loud: Error aborts the current operation instead of degrading it.

Applying it

The primary signature is export function asUserId(value: string)

The demo output is labeled (loading user), so every printed line maps back to its originating operation.

The surface worth importing is asUserId; the helpers around it are private to the snippet.

Statements that matter

if (!/^usr_[a-z0-9]+$/.test(value)) throw new Error("invalid user id");

Interactive Tools for This Topic

FAQ

How does the snippet fail?
`Error` is raised at the guard, so invalid state never reaches the main logic.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `asUserId`, `loadUser` at load time.