Developer Tools & Web Engineering

From Raw JSON to Strict TypeScript Interfaces: Runtime Schema Validation & Type Inference

Eliminate "Cannot read properties of undefined" in TypeScript apps by pairing static JSON-to-TypeScript interfaces with runtime boundary validation.

By Cometflow Frontend Architecture Desk • Updated 2026-11-02

One of the most common misconceptions in modern frontend engineering is assuming that typing an API response with a TypeScript interface protects the application at runtime. Because TypeScript performs complete type erasure when compiling to JavaScript, any unexpected null or missing nested object from an external REST API or webhook will still throw a runtime TypeError.

Start by generating clean compile-time interfaces from your real API payloads with the JSON to TypeScript Interface Generator and validating raw JSON syntax in the JSON Formatter & Validator.

1. Transforming Nested JSON into Idiomatic TypeScript

// Generated TypeScript Interfaces from a Stripe-like Webhook Payload
export interface WebhookEventPayload {
  id: string;
  type: 'invoice.paid' | 'invoice.payment_failed';
  created: number;
  data: {
    object: InvoiceRecord;
  };
}

export interface InvoiceRecord {
  invoiceId: string;
  amountCents: number;
  currency: 'USD' | 'EUR' | 'INR';
  customerEmail: string | null;
  lineItems: Array<{
    sku: string;
    quantity: number;
    unitPriceCents: number;
  }>;
}

2. Guarding Network Boundaries with Type Predicates

Always treat await response.json() as unknown until verified by a lightweight runtime type guard or schema parser before passing data into React state hooks.

Frequently Asked Questions

Does TypeScript validate JSON responses from fetch() at runtime?

No. TypeScript types are completely erased during compilation. Writing const data: UserResponse = await res.json() is merely a compile-time type assertion—if the backend returns null or changes a field from a number to a string, the browser will still crash at runtime unless you validate the object shape.

How should I type heterogeneous arrays or nullable API fields?

Use explicit union types (such as string | null) for nullable database columns, and discriminated unions (tagged with a literal type field like kind: "success" | "error") for polymorphic API responses.