How to Add Type Safety to LLM Responses in TypeScript Using Zod

TypeScript developers using strict mode often lose type safety when integrating LLM API calls, as response content returns unnarrowed union types and JSON.parse yields 'any' by default. These two stacked issues allow malformed or missing data to silently flow into databases, causing runtime errors far removed from their source. The fix involves a typed helper function that filters and narrows content blocks using TypeScript's Extract utility, preventing unsafe property access on union members. Zod schemas are then applied to parse results, converting JSON.parse output from 'any' to 'unknown' before validation enforces correct types, formats, and domain rules. Together, these two changes restore end-to-end type safety from the LLM response through to the database write.
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