Sub topic 1
Why TypeScript types are not enough at runtime
TypeScript catches many mistakes before your program runs. It cannot tell you whether the data your program receives matches the types you wrote. This chapter explains why, shows how the gap causes real bugs, and sets up the idea that the rest of this tutorial builds on: describe the expected shape of data once, and check it when the program runs.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript: interfaces, type aliases, unions, and the
unknowntype. - JavaScript objects, arrays, and JSON, including
JSON.parse. - How to install an npm package and use ES module imports.
- How
try/catchhandles thrown exceptions.
You do not need any Zod knowledge yet. The only Zod code here is a short preview at the end.
Two phases, one program
A TypeScript program lives through two phases.
- Compile time. The compiler reads your source, checks types, and reports errors. Then it removes every type annotation and emits plain JavaScript.
- Run time. A JavaScript engine (Node.js, a browser, Deno, Bun) executes the emitted JavaScript. It has never seen your types.
The compiler checks that the parts of your code are consistent with each other. It cannot check values that do not exist until the program runs. Those values come from outside the program: network responses, files, user input, environment variables.
Type erasure
Types are erased during compilation, so nothing in the emitted JavaScript can ask "is this value a User?" An interface has no runtime representation at all.
interface User {
id: number;
name: string;
}
// After compilation, the interface is gone. This line is a type error:
// console.log(User);
// 'User' only refers to a type, but is being used as a value here.Because of this, you cannot write value instanceof User for an interface, and you cannot loop over an interface's fields to validate them. The structure you described to the compiler is not available to your running code.
Assertions and `any` are promises, not checks
Several common TypeScript features let data into your program with a type attached and no verification.
The first is JSON.parse, which returns any. Assigning an any value to a typed variable compiles without complaint:
interface User {
id: number;
name: string;
}
const text = '{"id": "7", "name": null}';
const user: User = JSON.parse(text); // compiles
console.log(user.id + 1); // prints "71", string concatenation
console.log(user.name.toUpperCase()); // TypeError: Cannot read properties of nullThe compiler believes user.id is a number, so the first line looks fine. At run time id is the string "7", so + 1 concatenates instead of adding. The second line crashes because name is null.
The second feature is the type assertion with as. It tells the compiler to trust you:
interface User {
id: number;
name: string;
}
async function loadUser(): Promise<User> {
const response = await fetch("https://example.com/api/user/1");
return (await response.json()) as User;
}response.json() returns Promise<any> in the standard library typings, and the assertion changes nothing about the actual value. If the server returns a different shape, loadUser still claims to return a User.
The generic form of the same promise appears in many libraries, for example a helper like get<User>(url). The type parameter is an assertion in disguise.
Where unchecked data enters
Any value that originates outside your source code is unchecked. The table lists the usual entry points and what typically goes wrong.
| Entry point | Typical type from the runtime | Common surprises | Column |
|---|---|---|---|
| `JSON.parse` output | `any` | Missing fields, `null` instead of a string, numbers sent as strings | |
| `fetch` response body | `any` via `response.json()` | API version changes, error payloads with a different shape | |
| Request body in a server handler | Often `any` or `unknown` | Clients send anything, including attacks | |
| `process.env` | `string \ | undefined` per key | Variable missing, `"abc"` where a number is expected |
| `FormData` and query strings | `string` or `File` | Everything is text, empty fields arrive as `""` | |
| `localStorage` and files | `string` | Data written by an older version of your app |
Even when the runtime gives you an honest type, such as string | undefined for process.env.PORT, the type only describes the container. It says nothing about whether the content is a valid port number.
What goes wrong
Unchecked data causes three kinds of failure, in rising order of difficulty.
- Immediate crash. A property access on
nullorundefinedthrows aTypeError. This is the best case, because you see it. - Silent wrong results. The
"7" + 1example above produces a plausible-looking wrong value. The program keeps running, and bad data may be stored or sent onward. - Delayed failure. A wrong value passes through several functions before something breaks. The stack trace points at the code that crashed, not at the boundary where the bad data came in.
There is also a security aspect. A server handler that trusts a request body typed as { role: "user" | "admin" } gives an attacker control over every field they choose to send. Type annotations do not stop that.
The manual fix and its cost
You can verify data by hand. The honest way to receive untrusted data in TypeScript is to type it as unknown, which forces you to narrow it before use:
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record.id === "number" && typeof record.name === "string";
}
const data: unknown = JSON.parse('{"id": 7, "name": "Ada"}');
if (isUser(data)) {
console.log(data.name.toUpperCase()); // ADA
} else {
console.error("Not a valid user");
}This works, and the value is User return type narrows data inside the if. It has three problems.
- Two sources of truth. The
Userinterface and theisUserfunction describe the same shape separately. Add a field to one and forget the other, and the compiler will not warn you. The guard can saytruefor data that no longer matches the interface. - No detail on failure. The function returns
false. It does not say which field failed or why, so you cannot give a useful error message. - Growth. Nested objects, arrays, optional fields, numeric ranges, and string formats multiply the code. Hand-written guards for large payloads are long and rarely tested.
The approach this tutorial takes
A schema library removes the duplication. You write one description of the data as a runtime value. The library uses it to check data when the program runs, and TypeScript derives the static type from it. Zod is such a library. Here is a preview, which later chapters explain in detail:
import { z } from "zod";
const User = z.object({
id: z.number(),
name: z.string(),
});
const result = User.safeParse(JSON.parse('{"id": "7", "name": null}'));
console.log(result.success); // falseThe schema User is a normal JavaScript object that exists at run time, so it can inspect data. The same schema also provides the TypeScript type, so there is nothing to keep in sync. The failed result also records which fields were wrong, which a boolean guard cannot do.
Runtime validation does not replace TypeScript. The two cover different ground:
- TypeScript checks that your own code uses values consistently.
- Validation checks that values arriving from outside match what your code expects.
The practical rule is to validate once, at the point where untrusted data enters, and let static types carry the guarantee through the rest of the program.
Edge cases to keep in mind
strictmode helps, but does not solve this. Settings such asstrictandnoImplicitAnycatch implicitanyin your code. They do not catch an explicitanythat a library function returns.- Types can be right today and wrong tomorrow. A hand-typed API response matches the server on the day you write it. Server changes and old stored data break it later, with no compiler error on your side.
- A passing type check on a test fixture proves little. Fixtures typed in your own code always match your types. Real input does not.
- Validation has a cost. Checking a large payload takes time. Validate at boundaries, not inside hot loops over data you have already checked.
Exercise
The code const config = JSON.parse(text) as { port: number }; compiles without errors. If text is '{"port": "8080"}', what is the type of config.port according to the compiler, what is its actual value at run time, and why does TypeScript not report a problem?
Show answer
The compiler treats config.port as a number, because the as assertion tells it to. At run time the value is the string "8080". TypeScript does not report a problem because types are erased during compilation and an assertion performs no check. It only overrides the compiler's view of the value. Any code that does arithmetic on config.port can then silently produce wrong results, such as string concatenation instead of addition.
Exercise
A teammate adds a required field email: string to the User interface but forgets to update the hand-written isUser guard. Does the compiler report an error? What is the consequence, and how does defining the shape once as a schema address it?
Show answer
The compiler reports no error, because the guard's body is ordinary code and the value is User return type is a claim the compiler accepts without checking the body. The guard now returns true for objects without an email, so code that uses user.email can crash or misbehave. With a schema, the same definition drives both the runtime check and the static type, so adding a field changes both at once and the two cannot drift apart.