Sub topic 12
Branding with zod
Assume you know TypeScript type aliases, generics, intersection types, and the difference between compile-time types and runtime values. This chapter focuses on using the [Zod](https://zod.dev) validation library to create branded values at the boundary of an application.
Why zod helps with brands
A TypeScript brand prevents incorrect assignments during compilation, but it does not validate data at runtime. Data from an HTTP request, database, or configuration file starts as untrusted JavaScript values.
Zod combines two steps:
- It checks a value at runtime.
- It returns a TypeScript type that reflects the validated result.
The brand method adds a compile-time-only brand to a Zod schema. The schema still describes the runtime validation rules.
Defining a branded schema
This schema accepts non-empty strings and brands the result as UserId:
import { z } from "zod";
const UserIdSchema = z.string().min(1).brand<"UserId">();
type UserId = z.infer<typeof UserIdSchema>;
function loadUser(id: UserId): void {
console.log("loading", id);
}
const id: UserId = UserIdSchema.parse("u_123");
loadUser(id);
// @ts-expect-error A plain string has not passed through the schema.
loadUser("u_123");UserIdSchema.parse returns the branded type when parsing succeeds. If the value is empty, not a string, or otherwise fails the schema, parse throws a ZodError.
The brand does not change the JavaScript value. At runtime, id is still the string "u_123". The brand exists in TypeScript's type system so that a plain string cannot accidentally reach a function that requires a validated identifier.
Parsing versus safe parsing
Use parse when invalid input should throw and be handled by an outer error boundary. Use safeParse when the caller should inspect the result without catching an exception.
import { z } from "zod";
const EmailSchema = z
.string()
.trim()
.email()
.brand<"Email">();
type Email = z.infer<typeof EmailSchema>;
function sendReceipt(to: Email): void {
console.log(`Sending receipt to ${to}`);
}
function readEmail(input: unknown): Email | null {
const result = EmailSchema.safeParse(input);
if (!result.success) {
console.error(result.error.issues);
return null;
}
return result.data;
}
const email = readEmail("[email protected]");
if (email !== null) {
sendReceipt(email);
}Here, input is unknown, which is appropriate for external data. The successful branch narrows result.data to Email. The caller cannot use the result as an email unless validation succeeded.
> callout note > Put Zod parsing at system boundaries. After a value has been parsed, pass the branded type through internal functions instead of repeatedly accepting plain strings and rechecking them.
Refining a schema before branding
Apply all runtime rules before calling brand. For example, a database identifier may require a prefix and a specific length:
import { z } from "zod";
const OrderIdSchema = z
.string()
.regex(/^ord_[a-z0-9]{8}$/)
.brand<"OrderId">();
type OrderId = z.infer<typeof OrderIdSchema>;
const orderId = OrderIdSchema.parse("ord_a1b2c3d4");The regular expression performs the runtime check. The brand then prevents OrderId from being confused with another branded string, such as UserId.
Limits and design choices
Zod brands do not make values immutable, encrypt them, or preserve the brand after arbitrary transformations. Operations that create a new value may return an unbranded type, so validate or reapply the schema at that point.
Do not use a type assertion to skip parsing:
const unsafe = "not-an-order" as OrderId;This compiles, but it defeats both the validation boundary and the purpose of the brand. Keep unchecked assertions inside small, well-reviewed adapters, if they are needed at all.
Exercise
Why does UserIdSchema.parse("u_123") provide stronger protection than "u_123" as UserId?
Show answer
parse checks the value at runtime and returns a branded type only after validation. The assertion changes only the compile-time view and performs no runtime check.