Skip to the solution
MediumFrontend10 min read

How do you safely work with JSON of unknown shape?

450 views

The problem

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.parse returns any, which switches type checking off and spreads silently; the fix is to treat parsed data as unknown
  • Narrow unknown with checks: typeof, Array.isArray, an isRecord helper, 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.parse throws a SyntaxError) and valid JSON of the wrong shape; a Result type 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, undefined or 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.

  • unknown
  • type-safety

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptunknown, type guards and a Result for parsed JSON
TypeScriptA tiny schema validator that infers its own type

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 47 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What's new to type in TypeScript 5.5+ libs β€” `Array.fromAsync`, `Set` methods, `Iterator` helpers?

Continue