Sub topic 1
Why TypeScript Types Are Not Enough at Runtime
Prerequisites
This chapter assumes basic TypeScript types, interfaces, and type aliases. You should also know JavaScript objects, JSON, npm packages, and try/catch.
Why TypeScript types are not enough at runtime
TypeScript checks your code before it runs. It removes type annotations during compilation, so types do not inspect values at runtime. Data received from an API, form, file, or environment variable can still be invalid.
type User = {
id: number;
name: string;
};
function greet(user: User): string {
return user.name.toUpperCase();
}
const data: User = JSON.parse('{"id":"wrong","name":null}');
greet(data); // Fails at runtimeThe type assertion tells the compiler what you expect. It does not validate the parsed value. Zod is a validation library that checks runtime data against a schema, which is an executable description of an expected shape.
Your first schemas: strings, numbers, and booleans
A Zod schema describes both a type and its runtime checks. Install Zod with npm install zod.
import { z } from "zod";
const Username = z.string().min(3);
const Port = z.number().int().min(1).max(65535);
const Enabled = z.boolean();
console.log(Username.safeParse("sam").success); // true
console.log(Port.safeParse(3000).success); // true
console.log(Enabled.safeParse("true").success); // falseThe min, int, and range methods add constraints beyond the basic JavaScript type.
Describing objects with `z.object`
Use z.object to validate an object with named fields.
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
const result = User.safeParse({
id: 7,
name: "Sam",
});
if (result.success) {
console.log(result.data.name);
} else {
console.error(result.error.issues);
}A missing nickname is valid because its schema is optional. Zod returns validated data only after all required checks pass.
One source of truth: deriving types with `z.infer`
Writing a separate interface can let the static type and runtime schema drift apart. z.infer derives the TypeScript type directly from a schema.
type User = z.infer<typeof User>;
// { id: number; name: string; nickname?: string | undefined }The schema protects runtime values, while the inferred type guides later code. Both come from one definition.
Exercise
Why does type User = ... alone fail to protect data returned by JSON.parse?
Show answer
TypeScript types are removed before runtime and do not validate the parsed value.