Introduction
You now know TypeScript's features. This last lesson is about using them together, so that the compiler does as much of the checking as possible. The ideas are simple to state: check data once, where it enters the program; design types so that wrong combinations cannot be written; and let the compiler prove that every case is handled. Programs built this way have fewer places where things can go wrong, and the compiler points at all of them.
How it works
Parse, don't validate. Raw input (text, JSON, form fields) is untrusted. Instead of checking it in many places, convert it once, at the edge of the program, into a value whose type proves it was checked. The parsing function returns a Result: success with the typed value, or an error. Everything inside the program then accepts only the typed value, and never needs to check again.
Make invalid states unrepresentable. An order modelled as { status: string; items?: string[]; total?: number; reason?: string } allows nonsense, such as a cancelled order with a total and no reason. A discriminated union lists the real states, each with exactly its own fields:
type Order =
| { status: "draft"; items: readonly string[] }
| { status: "placed"; items: readonly string[]; total: number }
| { status: "cancelled"; reason: string };
Now a cancelled order has a reason, and a draft has no total, by construction. Switches over status are checked for exhaustiveness, so a new state cannot be forgotten.
Brand look-alike values. An email, a user id and an order id are all strings, and nothing stops you passing one where another is expected. A branded type adds a phantom property that exists only in the type: type Email = string & { readonly __brand: "Email" }. A plain string is not an Email, so the only way to get one is through parseEmail, the one place that uses the assertion clean as Email after checking. A function taking an Email can rely on it.
Prefer readonly data. readonly properties and readonly T[] arrays document that a value is not changed, and make accidental changes compile errors. New states are made as new objects.
Finally, keep as assertions and any rare, and only where a check right next to them justifies them, as in a parsing function. Each one is a place where you, not the compiler, are responsible for the types being true.
Example
// A Result type, a branded type, and a discriminated union of states.
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };
type Email = string & { readonly __brand: "Email" };
function parseEmail(text: string): Result<Email> {
const clean = text.trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+\.[a-z]+$/.test(clean)) return { ok: false, error: "not an email: " + text };
return { ok: true, value: clean as Email };
}
function sendWelcome(to: Email): string {
return "welcome sent to " + to; // only a checked Email can get here
}
type Order =
| { status: "draft"; items: readonly string[] }
| { status: "placed"; items: readonly string[]; total: number }
| { status: "cancelled"; reason: string };
function describe(order: Order): string {
switch (order.status) {
case "draft":
return "draft with " + order.items.length + " items";
case "placed":
return "placed, total " + order.total;
case "cancelled":
return "cancelled: " + order.reason;
}
}
for (const text of [" Ada@Example.com ", "not-an-email"]) {
const r = parseEmail(text);
console.log(r.ok ? sendWelcome(r.value) : r.error);
}
console.log(describe({ status: "placed", items: ["pen"], total: 20 }));
console.log(describe({ status: "cancelled", reason: "out of stock" }));Line by line
Result<T, E>is success with a value or failure with an error.Emailis a string at run time, but onlyparseEmailcan produce one, after checking the text.sendWelcomeaccepts only anEmail, so it never sees unchecked text.Orderlists three states, each with its own fields;describehandles each, and the compiler knows the switch covers them all.- The loop shows both outcomes of parsing: a cleaned email and an error message.
Expected result
welcome sent to ada@example.com
not an email: not-an-email
placed, total 20
cancelled: out of stock
In the real world
Validation libraries such as Zod are popular because they implement "parse, don't validate": a schema checks unknown data and produces a typed value. Payment and banking code uses branded types for amounts, currencies and account numbers. State machines for checkouts, uploads and connections are modelled as discriminated unions so that impossible states, such as "uploaded but no file", cannot occur.
Common mistakes
- Checking the same input in many places, and missing one.
- Optional fields for everything, which allows combinations that make no sense.
- Using as to silence an error instead of fixing the types, which hides a real problem.
- Creating branded values outside their parsing function, which breaks the guarantee.
Best practices
- Write one parsing function per kind of input, returning a Result.
- Model each kind of object's states as a discriminated union with readonly fields.
- Treat every
as,anyand!in your code as something to justify in a comment.
Summary
A type-safe design parses raw input once into typed values, models states as discriminated unions so invalid ones cannot exist, brands look-alike values so they cannot be mixed, prefers readonly data, and reports expected failures with Result types. The compiler then checks the rules everywhere, and exhaustiveness checks make sure that every case is handled.
Quick check
Key takeaways
- Check raw input once, at the edge, and pass typed values everywhere else.
- Discriminated unions make invalid states impossible to write down.
- Branded types stop look-alike values from being mixed; create them only in a checking function.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.