TypeScript Types Don't Validate API Request Bodies at Runtime
A developer explains that TypeScript types are erased at runtime, so they cannot guarantee the shape of incoming API request bodies. Using a type assertion simply tells the compiler to trust the data, which can let malformed or malicious input through. The article describes concrete risks, including server crashes from unexpected values, corrupted stored data, and mass assignment that lets clients set privileged fields like role. The recommended fix is runtime schema validation with a library such as Zod, which rejects bad input with a 400 response and strips unknown fields. Treating every value crossing a program's boundary as untrusted is presented as the core principle.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in