Course contentsShow
← TypeScript
Lesson 869 of 1,79620. The any Escape HatchFree lesson

Dynamic JSON Parsing Without Schema

When parsing arbitrary JSON with unknown structure, any avoids premature type commitments before validation.

Dynamic JSON Parsing Without Schema

You'll learn how any helps you work with unpredictable JSON structures when you don't know the shape ahead of time.

The JSON Parsing Problem

When you call JSON.parse(), TypeScript infers the return type as any — and for good reason. The JSON string could contain anything: an object, an array, a number, a string, or deeply nested structures that change based on runtime conditions.

Without any, you'd be forced to declare a specific type upfront:

interface User {
  name: string;
  age: number;
}

const parsed: User = JSON.parse(jsonString);

But what if the JSON doesn't match that shape? What if it's actually an array? Or what if the structure varies by API version? Committing to a type before validation creates a dangerous lie.

Why any Is the Right Default

JSON.parse() returns any because it defers type decisions until after you've inspected the data:

const data = JSON.parse(apiResponse); // data: any

// Now you can safely narrow and validate
if (typeof data === 'object' && data !== null) {
  if ('name' in data && typeof data.name === 'string') {
    console.log(data.name.toUpperCase());
  }
}

This pattern acknowledges reality: the JSON structure is unknown at compile time. Using any here isn't a mistake — it's an honest admission that safety comes from runtime validation, not premature type annotations.

The Validation Workflow

any gives you breathing room to inspect the data before asserting its shape. Once validated, you can narrow to a concrete type or create type guards. Without any, you'd either lie about the type or fight TypeScript's inference system.

Key Takeaway: When parsing JSON with unknown structure, any prevents premature type commitments and lets you validate safely at runtime before narrowing to specific types.