Sub topic 8
Validating Input at the Boundaries of Your Program
Assume you know basic TypeScript types, generics, intersection types, and the difference between compile-time types and runtime values. This chapter focuses on one rule: create a branded value when untrusted data enters your program.
Why boundaries need validation
A boundary is a place where data enters your program from outside its type system. Common boundaries include:
- HTTP request bodies
- URL parameters
- Environment variables
- Database rows
- Files
- Message queues
TypeScript checks your source code, but it does not check data received at runtime. A value typed as UserId can still come from a user, a JSON document, or a database with an invalid value.
Use unknown for external data. Unlike any, unknown forces you to check the value before using it.
flowchart LR
External["Untrusted input"] --> Validate["Runtime validation"]
Validate --> Brand["Create branded value"]
Brand --> Domain["Domain code"]
Validate --> Reject["Reject invalid input"]Parse at the boundary
A parser is a function that checks an unknown value and returns a trusted domain value. The cast belongs inside the parser because the parser has just performed the required checks.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type UserId = Brand<string, "UserId">;
function parseUserId(value: unknown): UserId {
if (typeof value !== "string") {
throw new TypeError("User ID must be a string");
}
if (!/^u_[a-zA-Z0-9]+$/.test(value)) {
throw new Error("User ID must start with u_");
}
return value as UserId;
}
function loadUser(id: UserId): void {
console.log("Loading user", id);
}
function handleRequest(body: unknown): void {
if (typeof body !== "object" || body === null || !("userId" in body)) {
throw new Error("Request must contain userId");
}
const id = parseUserId(body.userId);
loadUser(id);
}
handleRequest({ userId: "u_123" });
// handleRequest({ userId: "bad" }); // throws before loadUser runsThe handleRequest function first checks the outer shape. It then passes the userId field to parseUserId. After parsing succeeds, the result has type UserId.
The rest of the program does not need to repeat the format check. It can accept UserId and rely on the boundary to produce only valid values.
Keep invalid data out
Validate each boundary once, as close to the boundary as possible. Do not accept a plain string deep inside the domain layer and hope that an earlier caller checked it.
This pattern also applies to constrained numbers, dates, and parsed configuration:
- Parse a positive integer from an environment variable.
- Parse an ISO date before storing it as a domain date.
- Parse an email address before passing it to notification code.
- Parse a database identifier before calling a repository method.
The boundary is also an error boundary
A parser should make failure explicit. You can throw an error, return a result object, or use a validation library. The choice depends on your application, but invalid input should not silently become a branded value.
For larger applications, collect boundary parsers in one module. Domain code then imports parseUserId or an equivalent validated API instead of using as UserId throughout the codebase.
Exercise
Why should a value from JSON be typed as unknown before it is converted to a branded type?
Show answer
JSON data has no compile-time guarantee. Using unknown forces runtime checks, while a direct cast could label invalid data as branded without validating it.