Question presented to candidate:
"You call JSON.parse on a request body or fetch(...).json() on an API response. How do you work with that data safely in TypeScript, given that the compiler has no idea what shape it has?"
What a strong answer should cover:
JSON.parsereturnsany, which switches type checking off and spreads silently; the fix is to treat parsed data asunknown- Narrow
unknownwith checks:typeof,Array.isArray, anisRecordhelper, type guards or assertion functions, field by field, and build a fresh object so unknown keys are not passed on - Handle the two failure modes separately: invalid JSON (
JSON.parsethrows aSyntaxError) and valid JSON of the wrong shape; aResulttype keeps both explicit - Schema validation libraries (Zod, Valibot and others) give one definition for the run-time check and the static type (
z.infer-style inference), avoiding drift between a hand-written type and a hand-written guard - JSON has no
Date,Map,undefinedor class instances: dates arrive as strings and need a reviver or explicit conversion - Why a type assertion (
as User) is not validation
Clarifying questions expected:
- Is the data from our own backend with a shared contract, or from a third party or user input?
- What should happen on invalid data: reject, fall back to defaults, or log and continue?
- Is a validation library already in the project, and does bundle size matter on the client?
Code / implementation expected: Yes β a parse wrapper returning unknown plus a type guard or schema that validates the shape.