Sub topic 8
Validating input at the boundaries of your program
This chapter assumes you can write generic TypeScript functions and know the Brand<T, B> helper from the earlier chapters. You should also be comfortable with the difference between compile-time types and runtime values. Branded types only pay off once you decide where branded values are allowed to come from. The usual answer is the boundaries of your program.
What a boundary is
A boundary is any place where data enters your program from outside the type checker's view. Examples:
- An HTTP request body or query string.
- The result of
JSON.parse. - Environment variables and command-line arguments.
- Rows read from a database or messages read from a queue.
- Values read from
localStorageor a file.
TypeScript knows nothing about the contents of these values. A function can declare that it returns Promise<User>, but the runtime data may not match. At a boundary the honest type is unknown.
Inside the boundary, your code should work with trusted, precisely typed values. A branded type records that a value passed a specific check. The boundary is where that check runs, and it is the only place that should produce branded values from raw input.
Parse, don't validate
A validating function checks a value and returns a boolean or nothing. The caller still holds the original unrefined type, so the knowledge is lost the moment the function returns. A parsing function takes a weaker type and returns a stronger one. With brands, the stronger type is the branded type.
Write each parser to accept unknown and return a result that is either a branded value or an error. A small Result type keeps the error path visible in the signature.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type Email = Brand<string, "Email">;
type Quantity = Brand<number, "Quantity">;
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const ok = <T>(value: T): Result<T, string> => ({ ok: true, value });
const fail = <T>(error: string): Result<T, string> => ({ ok: false, error });
function parseUserId(input: unknown): Result<UserId, string> {
if (typeof input !== "string") return fail("userId must be a string");
if (!/^u_[0-9]+$/.test(input)) return fail(`userId has the wrong format: ${input}`);
return ok(input as UserId);
}
function parseEmail(input: unknown): Result<Email, string> {
if (typeof input !== "string") return fail("email must be a string");
const trimmed = input.trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)) return fail(`invalid email: ${input}`);
return ok(trimmed as Email);
}
function parseQuantity(input: unknown): Result<Quantity, string> {
if (typeof input !== "number" || !Number.isInteger(input)) {
return fail("quantity must be an integer");
}
if (input < 1 || input > 100) return fail("quantity must be between 1 and 100");
return ok(input as Quantity);
}Two details matter here:
- Each
ascast sits directly after the check that justifies it. The cast is the one place where the compiler is told to trust you, so keep it next to its proof. parseEmailnormalizes the value before branding it. A parser can clean data as well as check it. The brand then promises "trimmed, lowercase, well formed", and no later code has to repeat that work.
Parsing a whole request
Real input arrives as an object with several fields. A parser for the object calls the field parsers and collects every error, so a client sees all problems in one response.
type CreateOrderRequest = {
userId: UserId;
contactEmail: Email;
quantity: Quantity;
};
function parseCreateOrder(body: unknown): Result<CreateOrderRequest, string[]> {
if (typeof body !== "object" || body === null) {
return { ok: false, error: ["body must be a JSON object"] };
}
const record = body as Record<string, unknown>;
const userId = parseUserId(record.userId);
const contactEmail = parseEmail(record.contactEmail);
const quantity = parseQuantity(record.quantity);
if (userId.ok && contactEmail.ok && quantity.ok) {
return {
ok: true,
value: {
userId: userId.value,
contactEmail: contactEmail.value,
quantity: quantity.value,
},
};
}
const errors: string[] = [];
if (!userId.ok) errors.push(userId.error);
if (!contactEmail.ok) errors.push(contactEmail.error);
if (!quantity.ok) errors.push(quantity.error);
return { ok: false, error: errors };
}The body as Record<string, unknown> cast is safe. It does not claim anything about the values, and every property read from record is unknown again, so each one still has to pass a parser.
Wiring it into a handler
The handler is the boundary itself. It converts raw text into unknown, runs the parser, and either responds with an error or passes a fully branded object inward.
function placeOrder(order: CreateOrderRequest): string {
return `Order for ${order.userId}: ${order.quantity} item(s), receipt to ${order.contactEmail}`;
}
function handleRequest(rawBody: string): { status: number; body: string } {
let data: unknown;
try {
data = JSON.parse(rawBody);
} catch {
return { status: 400, body: "Malformed JSON" };
}
const parsed = parseCreateOrder(data);
if (!parsed.ok) {
return { status: 422, body: parsed.error.join("; ") };
}
return { status: 200, body: placeOrder(parsed.value) };
}
console.log(handleRequest('{"userId":"u_42","contactEmail":" [email protected] ","quantity":3}'));
console.log(handleRequest('{"userId":"42","contactEmail":"nope","quantity":0}'));The first call prints status 200 with a normalized email. The second prints status 422 and lists all three problems. Note that JSON.parse returns any, and the code assigns it to a variable typed unknown. That assignment is what forces the parsers to run. Without the annotation, the any would flow through the program unchecked.
placeOrder has no validation code and does not check the quantity range. Its signature already states the preconditions. If a developer later writes a second caller that builds a CreateOrderRequest by hand with a plain number, the compiler rejects it.
Result values or exceptions
Both styles are common. Choose one per boundary and use it consistently.
| Style | Signature | Good for | Cost |
|---|---|---|---|
| Result value | `Result<T, E>` | User input, API requests, anything where invalid data is expected | More code at each call site |
| Throwing parser | `(x: unknown) => T` | Startup configuration, scripts, cases where invalid data is a bug | Failures are not visible in the type |
| Assertion function | `asserts x is T` | Narrowing a variable you already have, in place | Needs an explicit type annotation to call |
Invalid user input is normal, so it belongs in a Result. A missing DATABASE_URL at startup means the process cannot run, so throwing is appropriate:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Port = Brand<number, "Port">;
function parsePort(raw: string | undefined): Port {
const n = Number(raw);
if (raw === undefined || !Number.isInteger(n) || n < 1 || n > 65535) {
throw new RangeError(`PORT must be an integer from 1 to 65535, got ${String(raw)}`);
}
return n as Port;
}
const port = parsePort("8080");
console.log(`listening on ${port}`);Where boundaries sit
Draw the boundary as close to the outside as you can. These rules keep it effective:
- Parse once, near where the data enters. Do not pass
unknownor rawstringvalues deep into the program. - Do not re-validate branded values in core code. Trusting the brand is the point.
- Treat data from your own database as a boundary too. Rows can be older than your current rules, or written by another service. Parse them when loading.
- Keep the parsers and the brand casts in one module. Export the branded types and the parsers, and do not export a helper whose job is only to cast.
Common errors at boundaries
- Trusting
JSON.parsethrough a cast.JSON.parse(text) as CreateOrderRequestcompiles and checks nothing. The brands in that type are then false promises. - Branding in the wrong direction. Parsers should accept the weak type (
unknown) and return the strong one. A function that takes a branded value and returns a plain one throws information away. - Validating only the shape. Checking
typeof x === "string"and then casting toEmailskips the actual rule. The cast needs a check that justifies it. - Stopping at the first error. For user-facing input, return every problem at once, as
parseCreateOrderdoes. - Parsing late. If a raw string reaches a function six calls deep before being branded, the earlier functions had no protection.
Exercise
A teammate writes const user = JSON.parse(body) as { id: UserId; email: Email }; at the top of an HTTP handler and says the types are now safe. What is wrong, and how would you fix it?
Show answer
The cast does not check anything. JSON.parse returns any, so the compiler accepts the assertion, but id and email may be missing, the wrong type, or malformed, and they are labeled as UserId and Email anyway. Fix it by assigning the result to unknown, then running parseUserId and parseEmail on the fields (or one object parser) and only passing the branded values onward when every parser succeeds. Return an error response when any parser fails.
Exercise
Write the signature of a parser for a Percentage brand (a number from 0 to 100) that is meant for user-submitted form data and reports the reason for failure. Which of the three styles in the table fits, and why?
Show answer
function parsePercentage(input: unknown): Result<Percentage, string>. A Result value fits because invalid form data is expected, so the failure should be visible in the return type and handled by the caller instead of surfacing as an uncaught exception.