Sub topic 8
Handling JSON.parse results and caught errors
This chapter assumes you know basic TypeScript syntax (annotations, interfaces, union types), the JavaScript operators typeof and instanceof, and try/catch. You should also be able to run tsc or use an editor with TypeScript support. Earlier chapters covered unknown, narrowing, and user-defined type guards. Here you apply them where untyped data enters a program.
Why boundaries matter
A trust boundary is a place where data arrives from outside your type-checked code. Examples are a file you read, an HTTP response body, a message from another process, and a value caught from a throw. The compiler cannot see what is on the other side. Whatever type you give that data is a claim, not a fact.
If you type the data as any, you claim nothing and the compiler stops checking. If you type it as unknown, you admit you do not know yet, and the compiler makes you check before you use it. This chapter covers the two most common boundaries: JSON.parse and catch.
JSON.parse returns any
The standard library declares JSON.parse(text: string): any. The reason is that the result can be an object, an array, a string, a number, a boolean, or null. TypeScript has no way to know which from the string alone.
const data = JSON.parse('{"name":"Ada"}');
console.log(data.age.toFixed(2)); // compiles, throws TypeError at runtimeThe error appears only when the code runs, because data is any. The same problem exists in response.json() from fetch, which returns Promise<any>. A value typed any also spreads: anything you assign it to, return from it, or compute from it can become any too.
The first fix is to stop any at the boundary. Annotate the result as unknown the moment it comes out:
const raw: unknown = JSON.parse('{"name":"Ada","age":36}');
// raw.name; // error: 'raw' is of type 'unknown'Assigning any to unknown is always allowed. From this line on, raw is checked like any other value.
Parse, then validate
Handling JSON safely takes two steps, and each one has its own failure mode.
- Parsing can throw a
SyntaxErrorif the text is not valid JSON. - Validation can fail if the text is valid JSON but has the wrong shape.
Keep the two failures separate. A thrown error and a "wrong shape" result need different handling.
A reusable record check
Objects, arrays, and null all have typeof equal to "object". A guard for object-shaped data needs to rule out the last two. A small helper keeps that logic in one place:
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}Inside a function that has passed isRecord, you can read value.name and get unknown. That is the right type for a property you have not yet checked.
A guard for a specific shape
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
isRecord(value) &&
typeof value.name === "string" &&
typeof value.age === "number"
);
}The return type value is User is a promise you make to the compiler. The compiler does not verify that the body matches the interface. If you later add a field to User and forget to update the guard, the code still compiles. The guard then lets incomplete data through as a User.
Putting the steps together
A function that returns a result object makes both failure modes visible to callers:
type ParseResult<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
function parseUser(text: string): ParseResult<User> {
let raw: unknown;
try {
raw = JSON.parse(text);
} catch (err: unknown) {
return { ok: false, error: `Invalid JSON: ${errorMessage(err)}` };
}
if (!isUser(raw)) {
return { ok: false, error: "JSON does not match the User shape" };
}
return { ok: true, value: raw };
}
const inputs = ['{"name":"Ada","age":36}', "{", '{"name":"Ada"}'];
for (const input of inputs) {
const result = parseUser(input);
if (result.ok) {
console.log(result.value.name.toUpperCase());
} else {
console.error(result.error);
}
}The try block wraps only JSON.parse. A narrow try means a bug in your validation code is not mistaken for bad input. After the try/catch, TypeScript knows raw was assigned, because the catch branch returns.
The three inputs show three outcomes. The first parses and validates. The second throws a SyntaxError. The third parses but fails validation because age is missing.
Edge cases in validation
nulland arrays.JSON.parse("null")is valid and returnsnull.JSON.parse("[]")returns an array. TheisRecordhelper handles both.- Numbers that are not finite. JSON cannot encode
NaNorInfinity, so a parsed number is always finite. A value you build yourself and then check withtypeof x === "number"can still beNaN. AddNumber.isFiniteif that matters. - Extra properties. The guard above ignores fields it does not check. That is usually right for input you do not control. Decide this on purpose.
- Nested data. For nested objects and arrays, write a guard for each level and call them from each other. This gets long quickly.
Caught errors
JavaScript lets you throw any value, not only Error objects. throw "oops", throw 404, and throw null are all legal. Code you call, including libraries and rejected promises, can throw anything. So a caught value cannot be safely typed as Error.
useUnknownInCatchVariables
The compiler option useUnknownInCatchVariables types the catch variable as unknown. It is part of the strict family since TypeScript 4.4. With it on, using the variable without a check is a compile error:
try {
JSON.parse("{");
} catch (err) {
// console.log(err.message); // error: 'err' is of type 'unknown'
if (err instanceof Error) {
console.error(err.message);
} else {
console.error(String(err));
}
}With strict off, or with useUnknownInCatchVariables set to false, err is any and err.message compiles. You can also annotate the variable yourself, as in catch (err: unknown). TypeScript allows only any or unknown as that annotation. Writing unknown explicitly documents intent and keeps the code safe even if someone changes the compiler options.
A minimal tsconfig.json that turns this on:
{
"compilerOptions": {
"strict": true
}
}strict: true also enables noImplicitAny, which reports variables and parameters that would silently become any. You can switch off individual options after enabling strict, so check the final configuration if you see any where you do not expect it.
Narrowing a caught value
The usual pattern is instanceof Error, with a fallback for everything else. A reusable helper such as errorMessage above keeps catch blocks short. Know these limits:
instanceofcan fail across realms. AnErrorcreated in another iframe, or in a different Node.jsvmcontext, has a differentErrorconstructor.instanceof Errorreturnsfalsefor it. If you work across realms, also check for a stringmessageproperty with a guard.String(err)on an object gives"[object Object]". UseJSON.stringifyinside its owntryif you need to log a thrown plain object. It can throw on circular structures.- Custom error classes narrow naturally.
err instanceof NotFoundErrorgives you the subclass fields. This works when you control the throwing code and use classes.
Promise rejections are still any
The catch clause is not the only place caught values appear. In promise.catch((reason) => ...), the standard library types reason as any. The useUnknownInCatchVariables option does not affect it. Annotate it yourself:
async function load(): Promise<void> {
await Promise.reject("network down").catch((reason: unknown) => {
console.error(reason instanceof Error ? reason.message : String(reason));
});
}
load();When you use async/await with try/catch, the catch variable follows the compiler option as usual. That form is often the simpler choice.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| `const user = JSON.parse(text) as User` | The assertion removes checking and validates nothing. | Parse to `unknown`, then use a guard. |
| `catch (err: any)` | The variable is unchecked again. | Use `unknown` and narrow. |
| `if (typeof raw === "object")` as the only check | `null` and arrays also pass. | Use a helper such as `isRecord`. |
| A guard that returns `true` too easily | The compiler trusts it, so wrong data becomes a typed value. | Test guards with bad input, not only good input. |
| Wrapping parse and validation in one large `try` | Bugs in your code look like bad input. | Wrap only `JSON.parse`. |
Summary of the pattern
- Receive external data as
unknown, neverany. - Catch parse errors in a narrow
tryand narrow the caught value withinstanceofor a guard. - Validate shape with user-defined guards, or a schema library for larger data.
- Return a typed value or an explicit error. Do not let unchecked data travel further into the program.
Exercise
The function below compiles but can crash at runtime. Rewrite it so that bad input returns null instead of throwing, and so that no any is used. It should accept the text {"port": 8080} and return 8080.
function readPort(text: string): number | null {
const config = JSON.parse(text);
return config.port;
}
Show answer
Parse into unknown, catch the syntax error, and check the shape before reading port.
function readPort(text: string): number | null {
let raw: unknown;
try {
raw = JSON.parse(text);
} catch (err: unknown) {
return null;
}
if (
typeof raw === "object" &&
raw !== null &&
"port" in raw &&
typeof raw.port === "number"
) {
return raw.port;
}
return null;
}
The in check narrows raw to an object with a port property of type unknown (TypeScript 4.9 or later), and the typeof check narrows that property to number. Invalid JSON, null, arrays without a port, and a non-number port all return null.
Exercise
With strict enabled, why does catch (err) { console.log(err.message); } fail to compile, and what is the smallest change that makes it compile safely?
Show answer
useUnknownInCatchVariables (part of strict) types err as unknown, and you cannot read a property on unknown. The smallest safe change is to narrow first: if (err instanceof Error) { console.log(err.message); }. Adding an else branch that logs String(err) covers thrown values that are not Error objects. Changing the annotation to any would also compile, but it brings back the unchecked access this option prevents.