153: TypeScript - Why Types at Runtime Boundaries
Learning outcomes
- distinguish compile-time guarantees from runtime validation;
- configure a strict TypeScript project and read compiler errors;
- identify boundaries that deserve explicit types.
Study
TypeScript checks a program before it runs. It does not validate JSON, form values, database documents, or JavaScript callers at runtime. Treat types as a design language and validators as the executable boundary contract. Start with strict: true; relax a rule only with a documented reason.
Practice
Create a strict project and model a task boundary. Compile it, intentionally introduce an invalid status and an unchecked API response, then fix both without using any. Record which guarantees disappear after compilation.
Mental model
The compiler sees declarations and control flow; it does not see the future HTTP response. This is safe:
type Task = { id: string; title: string; status: 'open' | 'done' }
function label(task: Task) {
return task.status === 'done' ? `${task.title} (complete)` : task.title
}
This is not validation:
const task = JSON.parse(responseText) as Task
The assertion only suppresses compiler doubt. A malicious or outdated server can still send { title: 3 }. Parse unknown data at the boundary, then allow the rest of the program to rely on the parsed type.
Edge cases
- A JavaScript caller can bypass declarations unless the runtime boundary validates.
strictNullChecksmakes missing values visible instead of silently accepted.noUncheckedIndexedAccessmakes array and record lookups acknowledge absence.- A third-party package can have inaccurate declarations; isolate and test the adapter.
Interview questions
- Why does TypeScript not protect an Express route from malformed JSON?
- When is a type assertion justified, and what evidence should surround it?
- Which strict compiler option found a real bug in your exercise?
Checkpoint
Explain why unknown is safer than any, where a type assertion can lie, and which three boundaries in the task manager need runtime validation.
