实现说明
品牌类型区分领域 ID以函数 asUserId、asOrderId、loadOrder为骨架。
失败是响亮的:Error 在守卫分支上直接中止当前操作,不做降级。
常见问题
前置条件不满足时如何报错?
代码会拒绝继续:抛出 Error,此时状态仍可恢复。
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 asUserId、asOrderId、loadOrder。
主签名形如 function asUserId(raw: string)
核心语句
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}`;
代码示例
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);