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.
JSON.parse returns any, which turns type checking off for everything it touches. Return unknown instead and let a guard earn the type.
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');3
not a pointThe 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.