Sub topic 12
Branding with zod
This chapter assumes you know the hand-written Brand<T, B> helper from earlier in this tutorial, and that you can read basic zod schemas. It covers the zod library's own brand method. You will see what it produces, how it fits boundary validation, and where it differs from a hand-rolled brand.
Why use a library for brands
Earlier chapters built brands by hand. You wrote a Brand type, then a smart constructor that validated a value and cast it. That works, but it splits one fact across two places: the validation rule lives in a function, and the type lives in a type alias. They can drift apart.
zod is a schema library. A schema describes a shape and checks data against it at runtime. Its brand method attaches a brand to a schema, so one declaration holds the rule and the type. Parsing data with that schema both validates it and returns the branded type.
The basic pattern
import { z } from "zod";
const UserId = z.string().min(1).brand<"UserId">();
type UserId = z.infer<typeof UserId>;
const id: UserId = UserId.parse("u_123"); // validated at runtime, branded at compile time
function loadUser(id: UserId): void {
console.log("loading", id);
}
loadUser(id);
loadUser("u_123"); // Error: string is not assignable to UserIdThree things happen here.
z.string().min(1)builds a schema that accepts non-empty strings..brand<"UserId">()returns a schema of the same runtime behavior. Its output type is nowstring & z.BRAND<"UserId">.type UserId = z.infer<typeof UserId>extracts that output type. Aconstand atypecan share a name because they live in different namespaces. This is a common zod convention, and it lets you import one name for both uses.
parse is the smart constructor. It returns the branded value if validation passes and throws a ZodError if it does not. The compiler rejects the plain literal "u_123" in the last line because nothing proved it valid.
What `brand` does at runtime
Nothing. The brand is erased like any other type. The runtime value is still an ordinary string, and brand() adds no wrapper, property, or check. All validation comes from the other methods in the chain, such as min(1).
This has a consequence worth stating plainly. A brand is a compile-time claim that "this value passed through this schema". The brand itself verifies nothing. If you brand a schema with no checks, such as z.string().brand<"Anything">(), every string passes and receives the brand.
Input type versus output type
A zod schema has two types: the input it accepts and the output it produces. The brand applies only to the output.
import { z } from "zod";
const Quantity = z.number().int().positive().brand<"Quantity">();
type QuantityInput = z.input<typeof Quantity>; // number
type QuantityOutput = z.output<typeof Quantity>; // number & z.BRAND<"Quantity">
type QuantityDefault = z.infer<typeof Quantity>; // same as z.output
const q: QuantityOutput = Quantity.parse(3);
function reserve(quantity: QuantityOutput): string {
return `reserved ${quantity}`;
}
console.log(reserve(q));z.infer is an alias for z.output. This split is what you want. Callers can feed plain numbers into the parser, and everything downstream receives the branded type. When a schema also uses transform, the brand sits on the transformed result, because that is the output.
Parsing at the boundary
The main use of zod brands is at the edge of your program, where untrusted data arrives. Put brands on the fields of an object schema and parse the whole payload once.
import { z } from "zod";
const UserId = z.string().min(1).brand<"UserId">();
const Email = z.string().email().brand<"Email">();
const Age = z.number().int().min(0).max(150).brand<"Age">();
const SignupBody = z.object({
id: UserId,
email: Email,
age: Age,
});
type Signup = z.infer<typeof SignupBody>;
function handleSignup(body: unknown): Signup | null {
const result = SignupBody.safeParse(body);
if (!result.success) {
console.error(result.error.issues);
return null;
}
return result.data; // id, email, and age are all branded here
}
const ok = handleSignup({ id: "u_1", email: "[email protected]", age: 30 });
const bad = handleSignup({ id: "", email: "nope", age: -1 });
console.log(ok, bad);safeParse returns a result object instead of throwing. When success is true, result.data has the branded types. Inside the program, functions that take Email or UserId can trust their arguments, because the only route to those types goes through the schema.
Composing brands
Calling brand on a branded schema stacks the brands by intersection. The result is assignable to each of its parts, which matches the refinement idea from the composition chapter.
import { z } from "zod";
const Email = z.string().email().brand<"Email">();
const VerifiedEmail = Email.brand<"Verified">();
type Email = z.infer<typeof Email>;
type VerifiedEmail = z.infer<typeof VerifiedEmail>;
function logEmail(to: Email): void {
console.log("email", to);
}
function sendNewsletter(to: VerifiedEmail): void {
console.log("sending to", to);
}
const verified = VerifiedEmail.parse("[email protected]");
const unverified = Email.parse("[email protected]");
logEmail(verified); // OK: a VerifiedEmail is also an Email
sendNewsletter(verified); // OK
sendNewsletter(unverified); // Error: missing the "Verified" brandLook at what VerifiedEmail.parse actually checks: only the email format. The word "Verified" is a label, not a check. A real verification step, such as a confirmation link, happens elsewhere. If you want the type to mean something, produce VerifiedEmail only in the code that performs that step, for example with a function that takes an Email, checks a database, and returns VerifiedEmail.parse(email). Otherwise the brand overpromises.
Differences from a hand-rolled brand
| Aspect | Hand-written `Brand<T, B>` | zod `.brand<B>()` |
|---|---|---|
| Where the rule lives | A separate constructor function | In the schema, next to the brand |
| Creating a value | Your own `parseX` function | `schema.parse` or `schema.safeParse` |
| Error reporting | Whatever you throw | A structured `ZodError` with issue paths |
| Dependency | None | zod at runtime |
| Compatibility | Your own tag symbol | zod's own tag type |
The last row matters. zod's tag is a different type from your own Brand helper, so the two do not interoperate. A value branded by zod as Email is not assignable to a hand-written Email, and the reverse is also true. Pick one system per concept and keep to it. The exact shape of the tag type has changed between zod major versions, so treat it as an implementation detail and refer to your schemas through z.infer.
Pitfalls that remain
zod does not fix the limits you already know. These still apply:
- Casts bypass everything.
"x" as UserIdcompiles, because assertions override the checker. Keep casts out of application code and, where you can, ban them in code review or with a lint rule. - Brands do not survive serialization.
JSON.stringifyturns aUserIdinto a plain string, andJSON.parsereturns data the compiler cannot vouch for. Parse again with the schema whenever data crosses a process, network, or storage boundary. - Only the parse path is checked. If other code builds the same object literal by hand and casts it, the brand is false. Export the schema, and have the rest of the code obtain values by parsing.
- Brands alone do not enforce meaning.
z.string().brand<"Slug">()with no regex gives a type with no guarantee. Review each branded schema for the checks that justify its name. - Version differences. The names of helper types and a few
brandoptions differ between zod major versions. Check the documentation for your installed version before relying on anything beyondbrand<"Name">()andz.infer.
Choosing zod brands
Use zod brands when you already use zod to validate input, because the brand costs one method call. Use hand-written brands when you want no runtime dependency, or when the type lives in a small shared library. In either case, the design rule is the same: one narrow door through which values get their brand, and a type that says only what that door actually checks.
Exercise
In the schema const Quantity = z.number().int().positive().brand<"Quantity">();, what are z.input<typeof Quantity> and z.infer<typeof Quantity>, and why does reserve(5) fail to compile when reserve takes z.infer<typeof Quantity>?
Show answer
z.input<typeof Quantity> is plain number, and z.infer<typeof Quantity> is number & z.BRAND<"Quantity">, because the brand applies only to the output type. The literal 5 is a plain number that never passed through the schema, so it lacks the brand and the compiler rejects it. Calling reserve(Quantity.parse(5)) compiles.
Exercise
You define const VerifiedEmail = Email.brand<"Verified">(); and call VerifiedEmail.parse(userInput) in a request handler. A teammate says this proves the address was verified. Is that correct?
Show answer
No. parse runs only the checks defined on the schema, which here means the email format. The "Verified" brand is a label that the compiler tracks, and nothing checks it at runtime. To make the brand true, create VerifiedEmail values only in the code that performs the real verification, such as confirming a token, and keep the schema from being used on arbitrary input.