Parsing JSON Safely with unknown
What you'll learn: How to handle JSON parsing results using unknown to catch structure mismatches before they cause runtime crashes.
JSON.parse() is one of the most common sources of runtime errors in TypeScript applications. The function returns any by default, which means TypeScript won't help you catch mistakes when the actual JSON structure doesn't match what you expect.
The Core Problem
When you parse JSON, you're converting a string into a JavaScript object at runtime. TypeScript has no way to verify what's actually in that string — it could be anything. If you immediately trust the result and treat it as a specific shape, you're setting yourself up for crashes:
// Dangerous: assumes JSON structure without checking
const data = JSON.parse(userInput); // type is 'any'
console.log(data.user.email); // crashes if structure is different
The Safe Pattern with unknown
The solution is to treat JSON.parse() results as unknown, then validate the structure before using it:
const rawData: unknown = JSON.parse(userInput);
// Now you must narrow the type before accessing properties
if (typeof rawData === "object" && rawData !== null) {
const obj = rawData as Record<string, unknown>;
if ("user" in obj && typeof obj.user === "object" && obj.user !== null) {
const user = obj.user as Record<string, unknown>;
if ("email" in user && typeof user.email === "string") {
console.log(user.email); // Safe!
}
}
}
Think of unknown as a sealed package. You know something is inside, but you must open it carefully and check what you find before using it. any is like assuming the package contains exactly what you ordered without checking — sometimes you're right, sometimes you get a surprise.
Building a Validation Helper
Combine type guards with unknown to create reusable validators:
function isUserData(value: unknown): value is { user: { email: string } } {
if (typeof value !== "object" || value === null) return false;
const obj = value as Record<string, unknown>;
if (!("user" in obj)) return false;
const user = obj.user;
if (typeof user !== "object" || user === null) return false;
const userObj = user as Record<string, unknown>;
return "email" in userObj && typeof userObj.email === "string";
}
const rawData: unknown = JSON.parse(userInput);
if (isUserData(rawData)) {
console.log(rawData.user.email); // TypeScript knows this is safe
}
Key Takeaway: Always type JSON.parse() results as unknown and validate their structure with type guards before accessing properties — this catches data mismatches at runtime instead of crashing your application.