The Analogy: The Baggage Handling System at an Airport
An airport moves many thousands of bags a day through a chain of subsystems: check-in, screening, the sorting hall, the transfer belts, and finally delivery to the aircraft or the reclaim carousel. Each subsystem does one job and hands the bag on to the next through a clearly defined point, and the whole thing works only because of one arrangement made right at the start. Every bag is tagged once, at check-in, with a barcode that encodes a unique licence-plate number and the flight, and from that moment on no belt ever re-opens the suitcase to guess where it should go: it reads the tag and routes accordingly. A TypeScript project at scale is built the same way, as a set of modules each doing one job, with data validated once at the boundary and trusted throughout the interior thereafter.
The single tagging point is the load-bearing idea. Untrusted input arrives as a suitcase of unknown contents, and check-in is the one place where that unknown thing is inspected and turned into a trusted, structured record: a bag with a valid tag. Downstream belts do not each re-inspect the contents; they rely on the tag being correct because it was made correct at the edge. In a project this is the parse-at-the-boundary pattern: external data, an HTTP body, a file, an environment variable, is parsed once at the perimeter into a value of a precise internal type, and the rest of the code simply trusts that type rather than re-checking a raw shape at every function. The boundary is where doubt lives, so the interior does not have to.
The tags themselves carry a further discipline worth copying. A bag's licence-plate number is deliberately not interchangeable with a flight number or a seat number, even though all three are just digits, because a sorter that mistook a bag id for a flight id would load luggage onto the wrong aircraft. The system keeps these kinds apart by how each is issued and read, so a number meant for one slot cannot silently be used in another. In a project that discipline is a branded, or nominal, type: a UserId and an OrderId may both be strings or numbers underneath, but the type system treats them as distinct so one can never be passed where the other is expected, catching a whole class of mix-up that a bare number would wave through.
The failure mode is a bag that slips onto the belts without a proper tag, or a station that trusts a tag it never actually checked. An untagged bag flows downstream and is lost, exactly as unvalidated external data that flows past the boundary corrupts everything it touches, because the interior assumed the shape was already sound. Just as damaging is a porous boundary, validation done half-heartedly and repeatedly at every belt rather than properly once at check-in, which gives the worst of both worlds: repeated, scattered checks that are individually weak and still let bad data through. The rule the airport lives by, and the rule a well-architected project lives by, is one strong boundary and then trust. A project that tries to validate everywhere ends up trusting nowhere, and is both slower and, paradoxically, less safe than one with a single firm edge.
Syntax or Core Structure
The core architectural move is to parse untrusted input into a trusted type at one boundary function, which either returns a value of the exact internal type or fails. Everything past that point receives the trusted type and never re-checks the raw shape.
// src/boundary.ts
interface User {
id: number;
name: string;
}
// The boundary: unknown in, a trusted User out (or throw)
function parseUser(input: unknown): User {
if (
typeof input === "object" && input !== null &&
"id" in input && "name" in input &&
typeof (input as { id: unknown }).id === "number" &&
typeof (input as { name: unknown }).name === "string"
) {
const raw = input as { id: number; name: string };
return { id: raw.id, name: raw.name };
}
throw new Error("invalid user");
}
function loadOrReject(input: unknown): string {
try {
const user = parseUser(input);
return "ok:" + user.name;
} catch {
return "rejected";
}
}
console.log(loadOrReject({ id: 1, name: "ada" }));
console.log(loadOrReject({ id: "x", name: "ada" }));
console.log(loadOrReject("nope"));
Output:
ok:ada
rejected
rejected
parseUser is the check-in desk: it takes an unknown and either hands back a fully typed User or throws. The first call passes a well-formed object, so it parses and loadOrReject returns ok:ada. The second call has an id that is a string rather than a number, so the type check inside parseUser fails and it throws, giving rejected. The third passes a bare string, which is not an object at all, so it is rejected too. Past this boundary, any code holding a User can read user.name freely, because the doubt was resolved once at the edge.
Technical Depth: Branded Ids, Config, and Layering
Two patterns turn a pile of modules into an architecture: branded types that keep look-alike values apart, and a single validated config loaded once at start-up. A third concern, which direction modules may depend on, keeps the whole thing from tangling.
Branded ids keep look-alike values apart
A branded type intersects a primitive with a phantom marker, so two ids that are both numbers underneath become incompatible at the type level while staying plain numbers at runtime.
// src/branded.ts
type UserId = number & { readonly brand: "UserId" };
type OrderId = number & { readonly brand: "OrderId" };
function userId(value: number): UserId {
return value as UserId;
}
function orderId(value: number): OrderId {
return value as OrderId;
}
function describeUser(id: UserId): string {
return "user#" + id;
}
const u = userId(7);
const o = orderId(42);
// describeUser(o) would NOT compile: an OrderId is not a UserId
console.log(describeUser(u));
console.log(u + 1);
console.log(u + o);
Output:
user#7
8
49
At the type level UserId and OrderId are distinct, so describeUser(o) is rejected by the compiler even though both are numbers, which is exactly the bag-tag-versus-flight-number protection. At runtime the brand is erased: describeUser(u) prints user#7, u + 1 is plain arithmetic giving 8, and u + o is 7 + 42 = 49. The brand costs nothing at runtime and buys a whole class of caught mix-ups at compile time.
A typed config loaded once
Environment values are strings of unknown presence. Loading them once through a required-key helper, converting types, and freezing the result gives the rest of the app a single trusted config object.
// src/config.ts
interface Config {
port: number;
retries: number;
}
function getRequired(env: Record<string, string | undefined>, key: string): string {
const value = env[key];
if (value === undefined) {
throw new Error("missing env: " + key);
}
return value;
}
function loadConfig(env: Record<string, string | undefined>): Config {
return Object.freeze({
port: Number(getRequired(env, "PORT")),
retries: Number(getRequired(env, "RETRIES")),
});
}
const config = loadConfig({ PORT: "8080", RETRIES: "3" });
console.log(config.port);
console.log(config.retries);
console.log(config.port + config.retries);
Output:
8080
3
8083
getRequired is a tiny boundary of its own: a missing key throws at start-up rather than surfacing as a mysterious undefined deep in a request handler. loadConfig reads both keys, converts them to numbers, and freezes the object so nothing can mutate the config later. The values print 8080 and 3, and 8080 + 3 = 8083. Loaded once at the perimeter, the typed Config is then trusted everywhere.
Which way dependencies may point
Architecture also means deciding which layer may import which. The table shows a common three-layer arrangement where dependencies point inward, toward the domain, and never back out.
| Layer | May import | Must not import |
|---|---|---|
| boundary | domain and app | nothing further out |
| app | domain | boundary |
| domain | nothing internal | app and boundary |
Reading the rows, the domain layer is the innermost and depends on nothing else in the project, the app layer sits above it, and the boundary layer is outermost and may see both. Keeping the arrows pointing inward means the core logic never depends on how data happened to arrive, which is what lets the boundary be swapped without touching the domain.
Real World Example: An Order Intake Pipeline
An order service receives raw order records from an external source and must turn them into trusted internal orders before anything else touches them. The pipeline parses each raw record at the boundary, rejecting anything malformed, brands the customer id so it cannot be confused with other numeric ids, and then reports the accepted orders and their total. Malformed records never reach the interior.
// src/intake.ts
type CustomerId = number & { readonly brand: "CustomerId" };
interface RawOrder {
customer: number;
amount: number;
}
interface Order {
customer: CustomerId;
amount: number;
}
// The boundary: a RawOrder becomes an Order, or null if invalid
function parseOrder(raw: RawOrder): Order | null {
if (raw.amount <= 0) {
return null;
}
return { customer: raw.customer as CustomerId, amount: raw.amount };
}
function pad(text: string, width: number): string {
const gap = width - text.length;
return text + " ".repeat(gap > 0 ? gap : 0);
}
const RAW: RawOrder[] = [
{ customer: 1, amount: 120 },
{ customer: 2, amount: 0 },
{ customer: 1, amount: 30 },
{ customer: 3, amount: 50 },
{ customer: 2, amount: -5 },
];
const orders: Order[] = [];
for (const raw of RAW) {
const parsed = parseOrder(raw);
if (parsed !== null) {
orders.push(parsed);
}
}
let total = 0;
console.log("raw: " + RAW.length);
console.log(pad("CUST", 6) + "AMOUNT");
for (const order of orders) {
total += order.amount;
console.log(pad(String(order.customer), 6) + order.amount);
}
console.log("accepted: " + orders.length + ", total: " + total);
Output:
raw: 5
CUST AMOUNT
1 120
1 30
3 50
accepted: 3, total: 200
Trace the five raw records. The first, third, and fourth have positive amounts, so parseOrder returns a typed Order for each. The second has an amount of 0 and the fifth has -5, both of which fail the amount <= 0 check and return null, so neither enters the orders array. The three accepted orders report amounts 120, 30, and 50, summing to 200, and the count is accepted: 3. Everything downstream of parseOrder works only with Order values, so no belt has to wonder whether an amount might be negative.
The value of this arrangement is that the boundary is the single place where a raw record is judged, and the branded CustomerId means an accepted order's customer cannot later be passed where, say, an order number is expected. The interior is small, typed, and free of defensive re-checks, which is the whole point of parsing once at the edge.
The design nonetheless has a real and instructive flaw. The boundary check is far weaker than it looks: parseOrder validates only amount, and brands the customer with raw.customer as CustomerId without checking it at all, so a garbage or negative customer number is stamped as a valid CustomerId and flows inward wearing a badge it did not earn, which is exactly the false confidence a brand can create when the cast is unchecked. Two further limits sit alongside: a rejected record returns null and simply vanishes with no record kept, so the report cannot distinguish "no such order" from "an order that was thrown away", the familiar zero-versus-unknown gap; and the report never groups by customer, so the two separate orders from customer 1 are shown as independent rows rather than aggregated, which a real billing view would almost certainly need to do.
Common Mistakes
- Validating the same data repeatedly through the interior. Scattering shape checks at every function is the porous boundary; parse once at the edge and trust the type afterwards.
- Letting untrusted input in as
any. Casting an HTTP body straight to a domain type skips the boundary entirely, so malformed data corrupts everything downstream unchecked. - Using a bare
numberorstringfor every id. Without branded types, a user id and an order id are interchangeable, so a mix-up compiles cleanly and fails only at runtime. - Branding with an unchecked
ascast. A brand applied without actually validating the value gives false confidence, because the type says trusted while the runtime value was never checked. - Reading environment variables ad hoc throughout the code. Scattered
process.envreads mean a missing key surfaces as a deep, mysteriousundefinedinstead of a clear start-up failure. - Leaving config mutable. A config object that is not frozen can be changed at runtime by any module, making its values impossible to reason about.
- Letting dependencies point outward. When the domain layer imports the boundary, the core logic becomes coupled to how data arrived and can no longer be tested or reused in isolation.
- Reaching for
aswhenever a type complains. Frequent casting is usually a sign the types are wrong at the source; fix the shape rather than overriding the compiler. - Dropping rejected input silently. Returning
nulland discarding it with no log or count hides how much data is being refused and why.
Best Practices
- Parse untrusted input once at the boundary. Turn an HTTP body, a file, or an environment value into a precise internal type at the perimeter, and trust that type everywhere inside.
- Brand your ids. Give
UserId,OrderId, and the like distinct nominal types so a value meant for one slot cannot be used in another. - Validate before you brand. Only apply a brand after actually checking the value, so the type's promise matches the runtime reality.
- Load and freeze config once. Read every required environment value at start-up through a helper that throws on a missing key, then freeze the typed result.
- Point dependencies inward. Keep the domain layer free of any import from the boundary or app layers so the core stays independent of delivery details.
- Prefer fixing types over casting. Treat a rash of
ascasts as a signal that a type is wrong upstream, and correct the source instead. - Surface rejected input. Count or log what the boundary refuses so a silent flood of malformed data cannot go unnoticed.
- Keep each module to one job. A module with a single clear responsibility and a defined handover is what makes the whole system, like the airport, comprehensible at scale.
Practice Exercises
- The Check-In Desk. Write a
parseProduct(input: unknown): Productboundary that validates anamestring and a positivepricenumber, returning a typedProductor throwing, and test it against one valid and two malformed inputs. - The Distinct Tags. Define branded
AccountIdandInvoiceIdtypes overnumber, write a function that accepts only anAccountId, and confirm the compiler rejects anInvoiceIdpassed to it. - The Env Guardian. Write
loadConfigthat readsPORTandTIMEOUTfrom an env record through a required-key helper, converts them to numbers, freezes the result, and throws a clear error when a key is missing. - The Honest Boundary. Extend the order intake so
parseOrderalso validates the customer id before branding it, and so rejected records are counted rather than silently dropped, then report both the accepted total and the rejected count.