Validate unknown JSON in TypeScript without a library
Abstract
JSON.parse returns any. Here is how to check untrusted data with type guards and a Result type, with working code and the exact output.
TypeScript types disappear at runtime. If a server, a file or a user sends you JSON, the compiler cannot tell you whether it has the shape you hoped for. This tutorial shows how to check untrusted data in plain TypeScript with a few small functions and no library.
The code was type-checked with TypeScript 7.0.2 in strict mode and run on Node 24.
The problem
JSON.parse returns any. Anything assigned from any skips type checking, so this compiles and may blow up later:
const user: { id: number; name: string } = JSON.parse(text);
The annotation is a wish, not a check. The fix is to treat parsed data as unknown, which forces you to narrow it before use.
Step 1: a record check
function isRecord(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
typeof null is 'object' in JavaScript, and arrays are objects too, so both are excluded explicitly. The v is ... return type is a type predicate: when the function returns true, TypeScript treats v as a record in that branch.
Step 2: a parse function that explains itself
A boolean says whether the data is valid but not why. Returning a result type gives the caller a reason:
type User = { id: number; name: string; email?: string };
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
export function parseUser(input: unknown): Result<User> {
if (!isRecord(input)) return { ok: false, error: 'expected an object' };
if (typeof input.id !== 'number') return { ok: false, error: 'id must be a number' };
if (typeof input.name !== 'string') return { ok: false, error: 'name must be a string' };
if (input.email !== undefined && typeof input.email !== 'string') {
return { ok: false, error: 'email must be a string when present' };
}
return { ok: true, value: { id: input.id, name: input.name, email: input.email } };
}
After each check, TypeScript narrows the property, so by the final line it knows input.id is a number and input.name is a string. The function builds a new object instead of returning the input, so any extra fields in the incoming data are dropped.
Step 3: use it
const samples = [
'{"id": 1, "name": "Ada", "email": "ada@example.com"}',
'{"id": "1", "name": "Ada"}',
'[1, 2, 3]',
'{"id": 2, "name": "Grace"}',
];
for (const text of samples) {
const data: unknown = JSON.parse(text);
const result = parseUser(data);
console.log(result.ok ? `ok ${result.value.name}` : `error: ${result.error}`);
}
Running it prints:
ok Ada
error: id must be a number
error: expected an object
ok Grace
Notice const data: unknown = JSON.parse(text). That line is what stops the any from spreading. The result.ok check also narrows the union: inside the true branch result.value exists, in the false branch result.error does.
What this approach does not do
- It only reports the first problem. A real form may want every error at once.
- Nested objects and arrays need their own checks. You can write a helper per type and compose them.
- It does not check ranges, formats or lengths unless you add them.
- Parsing can itself throw:
JSON.parsethrows on invalid JSON, so wrap it intryandcatchat the boundary.
At some size, hand-written checks become tedious and a schema library earns its place. For a handful of types, the code above is short enough to read in one go, which is the point.
Conclusion
Parse into unknown, narrow with type guards, and return a Result that says what went wrong. The types you declare then describe data you have actually checked.[1] The same habit helps when validating agent output, covered in the post on permissioned agent access.
Reviewer 2 asks whether the input was checked. The authors reply that it was parsed as
unknown, which is the type-system equivalent of looking sceptical. ↩︎