Skip to content

brand ​

带“标签”的类型。UserId 和 OrderId 字符串看起来一样,但 TypeScript 不允许把其中一个传给另一个。

签名 ​

ts
function brand<T, B extends string>(schema: Schema<T>, name: B): Schema<T & Brand<B>>

参数 ​

参数类型说明
schemaSchema<T>值存在时使用的 Schema
namestring标签名称

注意事项 ​

标签只存在于类型中 —— 运行时值不变。只能通过 Schema 校验获得带标签的值:这保证了代码中的每个 UserId 都经过了校验。

示例 ​

ts
const UserId = brand(pipe(string(), uuid()), 'UserId');
const OrderId = brand(pipe(string(), uuid()), 'OrderId');
type UserId = Infer<typeof UserId>;
type OrderId = Infer<typeof OrderId>;

function getUser(id: UserId) { /* … */ }

const orderId = parse(OrderId, req.params.id);
getUser(orderId);                 // TypeScript error
getUser('550e8400-…');            // TypeScript error too
getUser(parse(UserId, req.params.id)); // ok

另请参阅 ​