Your agent swaps orderId and customerId and the compiler says nothing: branded IDs, with the type errors as the migration worklist
Two string parameters in the wrong order compile, pass review and fail in production. Brand the IDs, let tsc list every call site, and add a gate that stops the agent casting its way back. About 30 minutes.

A refund endpoint takes refund(orderId, customerId, amountPence). The agent writes a caller in a hurry and passes the customer first. Both are strings. TypeScript compiles it, the linter is happy, the one test that exercises the path uses the same two fixture values for both, and the bug waits for a real customer.
The runtime outcome depends on the function. refund throws “No order cus_77”, which at least is loud. A neighbour such as ordersFor(customerId) called with an order ID just filters on equality, matches nothing and returns an empty array. A support agent sees “this customer has no orders”. Nothing throws.
Agents are prone to it for a boring reason: they write the call from the names they remember, and every ID in a typical codebase has the same type, so nothing pushes back. The fix is old and cheap, and it suits agents well. Give each ID its own type, so the swap is a compile error, and let tsc produce the list of places to change. The agent works through the list. The compiler, not a reviewer’s eyes, says when the list is empty.
This Playbook builds the whole thing in a small module: a branded type for each ID, parsers at the edge, type-level tests that prove the swap no longer compiles, and a 20-line gate that catches the two ways an agent will try to dodge it. Everything below was run on TypeScript 7.0.2 and Vitest 5.1.2. The technique, the prompt and the check work with any coding agent that can read files and run a shell.
The module you’re protecting
Here’s the starting point. Five functions, all keyed by plain strings.
// src/refunds.ts
export type Order = { id: string; customerId: string; totalPence: number; refundedPence: number };
const orders = new Map<string, Order>();
export function addOrder(order: Order): void {
orders.set(order.id, order);
}
export function findOrder(orderId: string): Order | undefined {
return orders.get(orderId);
}
export function refund(orderId: string, customerId: string, amountPence: number): Order {
const order = orders.get(orderId);
if (!order) throw new Error(`No order ${orderId}`);
if (order.customerId !== customerId) throw new Error(`Order ${orderId} is not ${customerId}'s`);
if (order.refundedPence + amountPence > order.totalPence) throw new Error("Refund exceeds total");
order.refundedPence += amountPence;
return order;
}
export function ordersFor(customerId: string): Order[] {
return [...orders.values()].filter((o) => o.customerId === customerId);
}
export function clear(): void {
orders.clear();
}
Before changing anything, pin the problem with a test that compiles. This is the evidence that the type system isn’t helping:
// test/swap.test.ts
import { expect, test } from "vitest";
import { addOrder, clear, refund } from "../src/refunds.js";
test("a swapped call compiles and fails only at runtime", () => {
clear();
addOrder({ id: "ord_1001", customerId: "cus_77", totalPence: 5000, refundedPence: 0 });
expect(() => refund("cus_77", "ord_1001", 500)).toThrow("No order cus_77");
});
Run npx tsc -p . and it exits 0. Run npx vitest run and it passes: one test, green, about a bug. That’s the starting state, and it’s worth seeing once, because it’s exactly what the agent sees when it decides everything is fine.
Step 1: one type per ID
A branded type is a string with a phantom tag that exists only at compile time. At runtime it’s still a plain string, so there’s no wrapper object, no allocation and nothing to serialise differently.
// src/ids.ts
declare const brand: unique symbol;
export type Brand<T, Name extends string> = T & { readonly [brand]: Name };
export type OrderId = Brand<string, "OrderId">;
export type CustomerId = Brand<string, "CustomerId">;
const ORDER = /^ord_[0-9]{4,}$/;
const CUSTOMER = /^cus_[0-9]{2,}$/;
export function parseOrderId(raw: string): OrderId {
if (!ORDER.test(raw)) throw new TypeError(`Not an order id: ${JSON.stringify(raw)}`);
return raw as OrderId;
}
export function parseCustomerId(raw: string): CustomerId {
if (!CUSTOMER.test(raw)) throw new TypeError(`Not a customer id: ${JSON.stringify(raw)}`);
return raw as CustomerId;
}
Two design points matter more than the type trick.
First, the parser is the only door. A branded type with no validating constructor is just a cast waiting to happen, so each ID gets a function that checks the format and returns the brand. The as inside that function is the one cast in the codebase that’s allowed, because it’s the one that’s earned.
Second, make the format check real. The regexes above encode “an order ID looks like ord_ plus digits”. That means a customer ID handed to parseOrderId fails at the edge with a message that names the problem, instead of travelling three layers down and failing as “not found”. Use whatever your real ID format is: a UUID check, a ULID length, a prefix.
Step 2: change the signatures and let tsc make the list
Now change the module. Swap string for the branded types in Order, in the Map key, and in every ID parameter. This is mechanical enough to do by hand in a small file, and the point of the exercise is what happens next.
// src/refunds.ts (changed lines)
import type { CustomerId, OrderId } from "./ids.js";
export type Order = { id: OrderId; customerId: CustomerId; totalPence: number; refundedPence: number };
const orders = new Map<OrderId, Order>();
export function findOrder(orderId: OrderId): Order | undefined { /* unchanged body */ }
export function refund(orderId: OrderId, customerId: CustomerId, amountPence: number): Order { /* unchanged body */ }
export function ordersFor(customerId: CustomerId): Order[] { /* unchanged body */ }
Run the compiler. The old test, which passes raw strings, now fails to build:
test/swap.test.ts(6,14): error TS2322: Type 'string' is not assignable to type 'OrderId'.
Type 'string' is not assignable to type '{ readonly [brand]: "OrderId"; }'.
test/swap.test.ts(6,30): error TS2322: Type 'string' is not assignable to type 'CustomerId'.
Type 'string' is not assignable to type '{ readonly [brand]: "CustomerId"; }'.
test/swap.test.ts(7,23): error TS2345: Argument of type 'string' is not assignable to parameter of type 'OrderId'.
Type 'string' is not assignable to type '{ readonly [brand]: "OrderId"; }'.
That output is the worklist. In a three-file module it’s three lines. In a real service it’s two hundred, grouped by file, with exact line and column numbers, and it shrinks monotonically as the work proceeds. That’s a better task definition than any prose prompt, and it’s the reason this migration suits an agent: the stopping condition is “tsc exits 0”, which the agent can check itself and a reviewer can reproduce.
Here’s a prompt that works in any agent that can run a shell:
Task: finish the OrderId and CustomerId migration.
1. Run `npx tsc -p .` and read the errors. They are the worklist.
2. Fix each error by changing the value's origin, never by casting.
- Data entering from outside (HTTP body, query string, queue message,
database row, environment) goes through parseOrderId or parseCustomerId
once, at the edge, and carries the branded type from there on.
- Code that already holds a branded value passes it through unchanged.
3. Do not write `as OrderId` or `as CustomerId` anywhere except src/ids.ts.
Do not change a parameter back to `string` to silence an error.
4. Do not edit or delete a test to make it compile. If a test passes the
wrong kind of ID, that test found a real bug: report it.
5. After each batch run `npx tsc -p .` and `npx vitest run`. Stop when both
are clean and `python3 scripts/id-gate.py` prints "id gate: clean".
Then list every parser call you added and why it sits where it does.
Rule 4 is there for a reason. When a test passes a customer ID where an order ID belongs, the compiler has found a bug the test suite was blind to, and an agent that wants a green build will happily “fix” the test by casting. Asking for a report turns those into findings.
Step 3: parse once, at the edge
The usual shape of the change is that the parser calls end up in one thin layer and the rest of the code just threads the types through. Here’s the handler for the refund endpoint:
// src/handler.ts
import { parseCustomerId, parseOrderId } from "./ids.js";
import { refund } from "./refunds.js";
export function handleRefund(body: { orderId: string; customerId: string; amountPence: number }) {
const order = refund(parseOrderId(body.orderId), parseCustomerId(body.customerId), body.amountPence);
return { orderId: order.id, refundedPence: order.refundedPence };
}
If the service already validates request bodies with Zod, use its brand support and skip the hand-written parser. Zod documents .brand() under “Branded types” on its API page, and it type-checked and passed here on Zod 4.6.7:
import { z } from "zod";
export const OrderIdSchema = z.string().regex(/^ord_[0-9]{4,}$/).brand<"OrderId">();
export type OrderId = z.infer<typeof OrderIdSchema>;
The inferred type is a brand, so OrderIdSchema.parse("ord_1001") yields an OrderId and safeParse("cus_77") fails. Pick one source of truth for the type, though: either ids.ts owns OrderId and the schema produces it, or the schema owns it and ids.ts re-exports. Two parallel definitions with the same name are two different types, and the compiler will tell you so at the worst moment.
Step 4: prove the swap no longer compiles
Fixing call sites is half the job. The other half is a test that fails if somebody weakens the types later, say by widening a parameter back to string or exporting an OrderId that’s secretly any. Vitest has type-level assertions through expectTypeOf, and its testing-types guide covers the --typecheck flag.
// test/swap.test.ts
import { expect, expectTypeOf, test } from "vitest";
import { type CustomerId, type OrderId, parseCustomerId, parseOrderId } from "../src/ids.js";
import { handleRefund } from "../src/handler.js";
import { addOrder, clear, ordersFor, refund } from "../src/refunds.js";
const orderId = parseOrderId("ord_1001");
const customerId = parseCustomerId("cus_77");
test("the two ids are different types", () => {
expectTypeOf(orderId).toEqualTypeOf<OrderId>();
expectTypeOf<OrderId>().not.toEqualTypeOf<CustomerId>();
expectTypeOf<OrderId>().toExtend<string>();
expectTypeOf<string>().not.toExtend<OrderId>();
});
test("swapped arguments no longer compile", () => {
// @ts-expect-error customerId is not an OrderId
expect(() => refund(customerId, orderId, 500)).toThrow();
// @ts-expect-error a raw string is not an OrderId
expect(() => ordersFor("ord_1001")).not.toThrow();
});
test("the boundary rejects a malformed id before any lookup", () => {
clear();
addOrder({ id: orderId, customerId, totalPence: 5000, refundedPence: 0 });
expect(handleRefund({ orderId: "ord_1001", customerId: "cus_77", amountPence: 500 })).toEqual({
orderId: "ord_1001",
refundedPence: 500,
});
expect(() => handleRefund({ orderId: "cus_77", customerId: "ord_1001", amountPence: 500 })).toThrow(
'Not an order id: "cus_77"',
);
});
The @ts-expect-error lines carry the weight. That directive is itself an error if the next line is fine, so the day somebody loosens refund to accept strings, tsc reports “Unused ‘@ts-expect-error’ directive” and the build fails. The swap becomes a regression test that lives in the compiler. Use toExtend rather than toMatchTypeOf: Vitest’s docs mark the latter as deprecated since expect-type v1.2.0.
Run both, because they check different things. npx vitest run executes the runtime assertions, and npx vitest run --typecheck also type-checks the test files. Both print the same result here:
Test Files 1 passed (1)
Tests 3 passed (3)
The --typecheck run adds a line, Type Errors no errors. Keep tsc -p . in CI regardless: it covers the type assertions even if somebody forgets the flag, because expectTypeOf is only checked when the compiler sees the file.
Step 5: close the two escape hatches
An agent that can’t get past a compile error has two cheap options. It can widen the parameter back to string, or it can cast. Both leave the build green, and neither shows up in a diff skim, because as OrderId looks like a type annotation to a tired reviewer. A short script makes both a failing check.
#!/usr/bin/env python3
"""Fail when an id slips back to a raw string, or a cast sidesteps the parsers."""
import pathlib, re, sys
RAW = re.compile(r"\b(\w*Id)\??\s*:\s*string\b") # orderId: string
CAST = re.compile(r"\bas\s+(OrderId|CustomerId)\b") # x as OrderId
ALLOWED_CAST = {"src/ids.ts"} # the only file that may cast
ALLOWED_RAW = {"src/handler.ts"} # the edge, where input arrives as text
bad = []
for path in sorted(pathlib.Path("src").rglob("*.ts")):
rel = path.as_posix()
for n, line in enumerate(path.read_text().splitlines(), 1):
if rel not in ALLOWED_RAW and (m := RAW.search(line)):
bad.append(f"{rel}:{n}: raw string id '{m.group(1)}'")
if rel not in ALLOWED_CAST and CAST.search(line):
bad.append(f"{rel}:{n}: cast to a branded id outside ids.ts")
print("\n".join(bad) or "id gate: clean")
sys.exit(1 if bad else 0)
On the migrated module it prints id gate: clean and exits 0. Now simulate the backslide: widen findOrder to take a string and cast inside it. tsc still exits 0, because the cast is legal, and that’s the whole problem. The gate does not let it through:
src/refunds.ts:11: raw string id 'orderId'
src/refunds.ts:12: cast to a branded id outside ids.ts
src/refunds.ts:16: cast to a branded id outside ids.ts
Exit code 1. Lines 12 and 16 are both casts because the substitution that produced the backslide touched both Map.get calls. Whatever the agent does, the check names the file and line.
This is a regex, not a parser, and it has limits. A parameter named id: string (no Id suffix) isn’t matched, and a destructured { orderId }: { orderId: string } is matched only because the text contains orderId: string. If your codebase has a naming convention for IDs, the rule is as good as the convention. A typed lint rule such as @typescript-eslint/consistent-type-assertions with assertionStyle: "never" is stricter, but it also bans every other cast, which is a bigger fight. Try the script first and tighten later.
Wire both commands into whatever runs before a commit or in CI:
npx tsc -p . && npx vitest run && python3 scripts/id-gate.py
Make it yours
The pattern doesn’t change across stacks, only the spelling.
For C#, the same idea is a readonly record struct OrderId(Guid Value) or OrderId(string Value). The compiler rejects a CustomerId where an OrderId is expected, and the worklist is the build output. EF Core needs a value converter to map the struct to a column, and System.Text.Json needs a converter, so budget for those two registrations, or the first query fails at runtime and not at build time. Those parts weren’t run for this article, so treat the C# shape as the standard approach and verify the converters against your EF Core and serialiser versions.
For a monorepo, put the ids.ts file in a shared package and import the types everywhere. Two packages that each define their own OrderId brand are incompatible with each other by design, which is the right behaviour and a confusing error message.
For a large codebase, don’t migrate everything in one go. Brand the one ID that causes the most grief first (usually the tenant or account ID, since swapping that one is a data leak), run the loop, merge, then do the next. Each ID is an independent change, so each gets its own small PR.
Numbers work too. A Brand<number, "Pence"> stops pence being added to pounds. The same gate pattern applies; change the regexes.
What goes wrong
The brand is a compile-time promise, and the compiler can only keep it for code it can see. Three places the promise leaks:
JSON.parsereturnsany, and anything assigned from it is whatever the next line says it is. If the parse result is typed with an interface that listsorderId: OrderId, the compiler believes it. Parse at the edge, always, and treat a deserialiser that produces a brand without a check as a cast in disguise.- Database rows have the same problem. A query helper that returns
Order[]from an untyped driver result is making a cast, so wrap that one place and keep it in the gate’s allowed list. - Test fixtures drift back to raw strings. Give tests a
makeOrder()helper that builds branded values, so the next agent session copies that and not anas OrderId.
There’s also a cost in readability: error messages mention { readonly [brand]: "OrderId"; }, which looks alarming the first time. The first line of each message still names the two types that disagree, and that’s the line to read.
Don’t bother when the module has one ID type, when IDs never cross a function boundary, or when the code is a prototype that will be deleted. The technique pays for itself where two or more IDs of the same underlying type meet in one function signature, which is most of a typical backend.
The first 15 minutes
Pick one function in your codebase that takes two or more string or number IDs. Add the two brands and parsers from Step 1, change that function’s signature, and run tsc. The errors are the callers you’d otherwise be trusting. Hand the list to your agent with the prompt above, add the @ts-expect-error test for the swap, and put the three-command check in your pre-commit hook.