← 中文资源

简体中文版本

品牌类型区分领域 ID

用品牌类型在编译期区分 userId 与 orderId:参数顺序写反变成编译错误,不再靠运行时排查串号。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

order ord_9001 for user u-42
string 4

实现说明

品牌类型区分领域 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);