Skip to content
jshacks.dev
TypeScript

Parse unknown JSON into a typed value safely

JSON.parse returns any, so wrap it to return unknown and check the shape with a type guard before using the data. Works on TypeScript 5 and later.

1 min read
Summarize in AI

JSON.parse returns any, which turns type checking off for everything it touches. Return unknown instead and let a guard earn the type.

point.tsTypeScript
type Point = { x: number; y: number };

function parseJson(text: string): unknown {
  return JSON.parse(text);
}

function isPoint(value: unknown): value is Point {
  return (
    typeof value === 'object' &&
    value !== null &&
    'x' in value &&
    'y' in value &&
    typeof value.x === 'number' &&
    typeof value.y === 'number'
  );
}

const good = parseJson('{"x":1,"y":2}');
if (isPoint(good)) {
  console.log(good.x + good.y);
}

const bad = parseJson('{"x":"1"}');
console.log(isPoint(bad) ? 'point' : 'not a point');
Text
3
not a point

The wrapper costs nothing at runtime and makes the unchecked value impossible to use by accident: good.x does not compile until isPoint has narrowed it. JSON.parse itself still throws on malformed text, so wrap the call in try when the input comes from outside. See [JSON.parse in the lib typings](https://github.com/microsoft/TypeScript/blob/main/src/lib/es5.d.ts), which declare the any return.

Keep guards for small shapes. When the data has nested objects, arrays or optional fields, a schema library is shorter and gives the error messages. Add the schema once at the boundary and every layer behind it can trust the type.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.