JSON and Dynamic Data Structures in TypeScript
What You'll Learn
You'll learn how to safely type data from JSON.parse, API responses, and other runtime sources without falling back to the unsafe any type.
The Core Challenge
When you parse JSON or receive data at runtime, TypeScript has no idea what shape that data actually has. By default, JSON.parse() returns any, which defeats the entire purpose of type safety. The same problem occurs with API responses, file reads, localStorage, and any other dynamic data source.
The temptation is to leave it as any or blindly assert a type. Both approaches are dangerous—they lie to the compiler about what you actually have.
The Safe Approach: unknown + Validation
Instead of any, treat runtime data as unknown and validate it before use:
// ❌ Unsafe: Assumes data matches User without checking
const user = JSON.parse(jsonString) as User;
// ✅ Safe: Treat as unknown, validate before using
const parsed: unknown = JSON.parse(jsonString);
function isUser(value: unknown): value is { id: number; name: string } {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number" &&
"name" in value &&
typeof value.name === "string"
);
}
if (isUser(parsed)) {
// Now TypeScript knows parsed is { id: number; name: string }
console.log(parsed.name.toUpperCase());
}
This pattern works for any dynamic data: API responses, form inputs, WebSocket messages, or configuration files.
Think of It Like Airport Security
any is like waving people through without checking their bags—fast, but unsafe. unknown is like requiring everyone to go through screening. You don't trust the data until you've verified it matches what you expect.
Practical Pattern for API Responses
async function fetchUser(id: number): Promise<{ id: number; name: string } | null> {
const response = await fetch(`/api/users/${id}`);
const data: unknown = await response.json();
if (isUser(data)) {
return data;
}
return null; // Invalid data
}
Key Takeaway: Always type JSON.parse results and runtime data as unknown, then narrow them with type guards or validation libraries. Never use any for dynamic data—it sacrifices all type safety exactly where you need it most.