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.
Code
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 4How 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.