TypeScript types are erased at compile time. No type information exists at runtime, so a User annotation on await res.json() guarantees nothing about what the server actually sent. TypeScript checks your code's internal consistency, not external data. At trust boundaries (HTTP responses, localStorage, URL params, postMessage, form input, environment variables, third-party scripts), you need runtime validation, ideally with a schema library (Zod, Valibot, ArkType, Effect Schema, TypeBox) that infers the static type from the schema, so types and checks can't drift. Also relevant: type stripping in Node (TypeScript syntax is simply removed and nothing is checked), and the few TS features that do emit runtime code (enums, namespaces, parameter properties, decorators).
interface User { id: string; email: string; createdAt: Date }
async function getUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json(); // `any` flows into User; nothing checked
}
const u = await getUser('1');
u.createdAt.getTime(); // runtime crash: JSON has a string, not a Date
u.email.toLowerCase(); // crash if the API renamed it to `emailAddress`
import { z } from 'zod';
const UserSchema = z.object({
id: z.string(),
email: z.string().email(),
createdAt: z.coerce.date(),
role: z.enum(['admin', 'member']).default('member'),
});
type User = z.infer<typeof UserSchema>; // single source of truth
async function getUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return UserSchema.parse(await res.json()); // throws a descriptive error on mismatch
}
safeParse returns a result object instead of throwing, which is better for form and user input. Validation also transforms (coercing dates, applying defaults, stripping unknown keys), so the rest of the app works with clean data.
API_URL is missing).localStorage, IndexedDB), which may come from an older app version, so migrate or validate it..ts files by stripping types with no type-checking. Run tsc --noEmit in CI.--erasableSyntaxOnly flags them.instanceof works only with classes (runtime values). Interfaces and type aliases can't be checked at runtime. Use type guards or schemas.postMessage, server functions.Spotted a mistake or a rights concern? Report an issue