Skip to content

brand ​

A type with a "tag". UserId and OrderId strings look the same, but TypeScript won't let you pass one instead of the other.

Signature ​

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

Parameters ​

ParameterTypeDescription
schemaSchema<T>The value schema when it is provided
namestringTag name

Notes ​

The tag exists only in types — at runtime the value is unchanged. A tagged value can only be obtained through schema validation: every UserId in the code has passed validation at some point.

Example ​

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

See also ​