Branded Types For Domain Ids

Keep userId and orderId apart at compile time with branded types, so a refactor cannot silently pass one where the other belongs.

TypescriptData Integrity

Code

typescriptsnippet
28 lines
declare const brand: unique symbol;

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

type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

function asUserId(raw: string): UserId {
  if (raw.trim() === '') throw new Error('user id required');
  return raw as UserId;
}

function asOrderId(raw: string): OrderId {
  if (!/^ord_/i.test(raw)) throw new Error('order id must start with ord_');
  return raw as OrderId;
}

function loadOrder(userId: UserId, orderId: OrderId): string {
  return `order ${orderId} for user ${userId}`;
}

const uid = asUserId('u-42');
const oid = asOrderId('ord_9001');
console.log(loadOrder(uid, oid));

// 参数顺序写反是编译错误,而不是运行时串号
// loadOrder(oid, uid);
console.log(typeof uid, uid.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

order ord_9001 for user u-42
string 4

How it works

Branded Types For Domain Ids comes down to the functions asUserId, asOrderId and loadOrder.

Invalid states are rejected up front: it throws Error instead of continuing with bad data.

Applying it

The main signature reads function asUserId(raw: string)

Statements that matter

if (!/^ord_/i.test(raw)) throw new Error('order id must start with ord_');
if (raw.trim() === '') throw new Error('user id required');
return `order ${orderId} for user ${userId}`;

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `asUserId`, `asOrderId`, `loadOrder` at load time.