Sub topic 8
Handling JSON.parse Results and Caught Errors
Assume you know TypeScript type annotations, interfaces, union types, and the JavaScript typeof, instanceof, and try/catch statements. This chapter focuses on trust boundaries: places where data enters your program without a reliable TypeScript type.
Why JSON.parse Needs a Safety Check
JSON.parse converts a JSON string into a JavaScript value. In TypeScript's standard library, its result is typed as any. That means the compiler allows you to use the result as if it had any shape:
const value = JSON.parse('{"name":"Ada"}');
console.log(value.name.toUpperCase()); // Compiles
console.log(value.age.toFixed()); // Also compilesThe second line fails at runtime because age is undefined. A useful boundary pattern is to assign the result to unknown. This prevents accidental use before validation.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
function parseUser(json: string): User {
const value: unknown = JSON.parse(json);
if (!isUser(value)) {
throw new Error("JSON does not contain a valid User");
}
return value;
}
try {
const user = parseUser('{"name":"Ada","age":36}');
console.log(`${user.name} is ${user.age}`);
} catch (error: unknown) {
console.error("Could not load user:", error);
}The isUser function is a user-defined type guard. Its return type, value is User, tells TypeScript that a successful return means the value can be treated as a User. The checks still happen at runtime. TypeScript types alone cannot validate JSON.
Caught Errors Are Also Unknown
JavaScript permits any value to be thrown:
throw "network failed";
throw { code: 503 };
throw new Error("network failed");Therefore, code should not assume that a caught value has a message property. With the useUnknownInCatchVariables compiler option, a catch variable is typed as unknown automatically. Narrow it before reading its properties.
function describeError(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
return String(error);
}
try {
JSON.parse("{");
} catch (error: unknown) {
console.error(describeError(error));
}instanceof Error is appropriate for ordinary JavaScript errors. The fallback handles strings, objects, and other thrown values. Converting an unknown value with String is safer than accessing an unverified property.
The Boundary Workflow
Treat parsing and error handling as a short pipeline:
A type assertion such as JSON.parse(text) as User only tells the compiler to trust you. It does not check the object. Use an assertion only when another mechanism has already validated the data, such as a schema validator or a guaranteed internal source.
Practical Rules
- Convert untrusted results to
unknownimmediately. - Validate required properties and their types.
- Use
instanceof Errorbefore reading error fields. - Keep validation near the boundary where data enters the program.
- Return a typed value from the boundary so the rest of the application needs fewer checks.
- Enable
strictanduseUnknownInCatchVariablesintsconfig.json.
Exercise
Why is const value: unknown = JSON.parse(text) safer than using the result of JSON.parse(text) directly?
Show answer
unknown prevents property access and method calls until runtime checks narrow the value to a usable type.