karawaci.kode

2026-09-19 · 9 min

TypeScript Branded Types: Enforce Domain Safety at Compile Time, Not at Runtime

Passing a userId where the function expected an orderId is the kind of bug that compiles, passes lint, and silently corrupts data in production. I debugged one of these at a fintech startup in the BSD Serpong corridor — the kind of office park where four different services share a monorepo and nobody agreed on ID conventions. A payment query was returning the wrong records because a string userId was being passed to a function that expected a string orderId. Same type. Different domain. TypeScript had nothing to say about it.

Branded types fix this at the compiler level. No runtime cost.

The Core Problem TypeScript’s Structural System Creates

TypeScript uses structural typing. Two types are compatible if their shapes match. That’s mostly a feature, but for primitive aliases it becomes a liability:

type UserId = string;
type OrderId = string;

function getOrdersByUser(userId: UserId, orderId: OrderId): Promise<Order[]> {
  // ...
}

const uid: UserId = "user_01JABC";
const oid: OrderId = "order_01JXYZ";

// TypeScript does NOT catch this swap:
getOrdersByUser(oid, uid);

Both UserId and OrderId are just string. The compiler sees two string arguments — perfectly valid. The bug ships.

What Branded Types Are

A branded type attaches a phantom type tag to a primitive. The tag exists only in TypeScript’s type system; it has no runtime value. The standard pattern uses an intersection type with a readonly unique symbol:

// Brand utility — define once, use everywhere
type Brand<T, B extends string> = T & { readonly __brand: B };

// Domain primitive types
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type AmountIDR = Brand<number, "AmountIDR">;  // always in the smallest unit (sen)
type TransactionId = Brand<string, "TransactionId">;

Now UserId and OrderId are structurally incompatible even though both wrap string. The compiler will reject any attempt to use one where the other is expected.

Constructor Functions: The Only Way In

You can’t produce a branded type from a plain literal — "user_01JABC" as UserId is technically valid, but it defeats the purpose. The right pattern is a smart constructor that validates the input and returns the branded type:

// Constructor for UserId — validates format before branding
function UserId(raw: string): UserId {
  if (!raw.startsWith("user_")) {
    throw new Error(`Invalid UserId format: "${raw}"`);
  }
  return raw as UserId;
}

function OrderId(raw: string): OrderId {
  if (!raw.startsWith("order_")) {
    throw new Error(`Invalid OrderId format: "${raw}"`);
  }
  return raw as OrderId;
}

function AmountIDR(raw: number): AmountIDR {
  if (!Number.isInteger(raw) || raw < 0) {
    throw new Error(`AmountIDR must be a non-negative integer (sen), got: ${raw}`);
  }
  return raw as AmountIDR;
}

The as cast happens exactly once, inside the constructor. Everywhere else in the codebase, the type flows through without casts. When this function throws, it means you caught a domain violation at the boundary — not buried three functions deep.

Integrating with Zod at the System Boundary

Smart constructors work well for manual construction. For HTTP request parsing, Zod’s .brand() is cleaner:

import { z } from "zod";

// Define once in your shared domain-types package
export const UserIdSchema = z
  .string()
  .startsWith("user_")
  .min(10)
  .brand<"UserId">();

export const OrderIdSchema = z
  .string()
  .startsWith("order_")
  .min(10)
  .brand<"OrderId">();

export const AmountIDRSchema = z
  .number()
  .int()
  .nonnegative()
  .brand<"AmountIDR">();

// Infer the branded types from schemas — single source of truth
export type UserId = z.infer<typeof UserIdSchema>;
export type OrderId = z.infer<typeof OrderIdSchema>;
export type AmountIDR = z.infer<typeof AmountIDRSchema>;

At your HTTP layer, parse the incoming request body with these schemas:

const CreateOrderSchema = z.object({
  userId: UserIdSchema,
  amount: AmountIDRSchema,
  items: z.array(z.object({
    productId: z.string().brand<"ProductId">(),
    quantity: z.number().int().positive(),
  })),
});

// In your Express/Fastify handler:
async function createOrderHandler(req: Request, res: Response) {
  const body = CreateOrderSchema.parse(req.body);
  // body.userId is UserId — branded, validated, ready for domain layer
  // body.amount is AmountIDR — guaranteed non-negative integer

  const order = await orderService.create(body.userId, body.amount, body.items);
  res.json(order);
}

Anything that comes out of CreateOrderSchema.parse() is already branded. Your domain functions receive typed, validated values — not raw string and number that could be anything.

Domain Functions That Enforce Their Contracts

With branded types in place, your service functions become self-documenting about what kind of IDs they accept:

// This function cannot accidentally receive an OrderId where UserId is expected
async function getUserPaymentHistory(
  userId: UserId,
  limit: number
): Promise<PaymentRecord[]> {
  return db.query(
    "SELECT * FROM payments WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2",
    [userId, limit]
  );
}

// This function cannot accidentally receive a UserId where OrderId is expected
async function cancelOrder(
  orderId: OrderId,
  requestedBy: UserId
): Promise<void> {
  await db.transaction(async (trx) => {
    const order = await trx.findOne("orders", { id: orderId });
    if (order.userId !== requestedBy) {
      throw new ForbiddenError("Order does not belong to this user");
    }
    await trx.update("orders", { id: orderId }, { status: "CANCELLED" });
  });
}

These function signatures are now machine-enforced contracts, not documentation. You can refactor with confidence — if you swap the argument order by accident, the compiler catches it immediately.

What Happens at Runtime

Nothing changes. Branded types are erased by the TypeScript compiler. A UserId at runtime is just a string. There is no wrapping, no boxing, no extra allocation. You can log it, serialize it to JSON, store it in Redis, and read it back — it’s still just the string "user_01JABC".

This is the key difference from value object classes. A class-based UserId would survive instanceof checks but complicate JSON serialization. The branded type version is transparent to every runtime system: databases, HTTP clients, caches, queues.

Organizing Branded Types in a Monorepo

If you’re running multiple services, define all domain primitive types in a shared package:

packages/
└── domain-types/
    ├── src/
    │   ├── ids.ts          # UserId, OrderId, ProductId, etc.
    │   ├── amounts.ts      # AmountIDR, AmountUSD
    │   └── index.ts
    └── package.json
// packages/domain-types/src/ids.ts
import { z } from "zod";

export const UserIdSchema = z.string().startsWith("user_").brand<"UserId">();
export type UserId = z.infer<typeof UserIdSchema>;

export const OrderIdSchema = z.string().startsWith("order_").brand<"OrderId">();
export type OrderId = z.infer<typeof OrderIdSchema>;

export const ProductIdSchema = z.string().startsWith("prod_").brand<"ProductId">();
export type ProductId = z.infer<typeof ProductIdSchema>;

Every service imports from @yourorg/domain-types. When the order service produces an OrderId and passes it to the notification service, both sides are using the same type definition. If one service changes how it handles order IDs, TypeScript errors surface everywhere in the monorepo, not just in the service that changed.

Where to Draw the Boundary

Not every string needs a branded type. Apply them where:

  1. Multiple ID types coexist in the same function signatures. If a function takes three different IDs, branding prevents silent argument swaps.
  2. Values have invariants that must be preserved. AmountIDR being a non-negative integer is a domain rule. The brand signals that this value has been validated.
  3. Values cross service boundaries. IDs that travel between services through queues, RPC calls, or HTTP are good candidates — the brand documents the expected provenance.

Don’t brand every string just because you can. email: string in a user profile model is fine unless you have multiple “kinds” of email (primary, verification, billing) that could be confused.

The Real Payoff

Branded types shift a category of domain bugs from “caught at runtime when a user hits the wrong data” to “caught at compile time when you type the wrong variable”. They add no runtime overhead, no new dependencies beyond Zod if you’re already using it, and no new abstractions that your team needs to learn beyond the initial Brand utility type.

The initial investment is defining your domain primitives and ensuring system boundaries produce branded values. After that, the compiler does the enforcement. On a large codebase with many contributors — the kind of team spread across BSD and Tangerang Kota, different timezones, different levels of domain familiarity — that’s the difference between a class of bugs that “sometimes happens” and one that structurally cannot.

Ditulis oleh Reza Pradipta