← All JSON guides

JSON guide · 2 min read

How to Generate TypeScript Interfaces from JSON

Generate TypeScript types from sample JSON, then review optional fields, nullability, unions, arrays and runtime validation before using them.

By JSON HearthPublished 2026-08-05Updated 2026-08-22

What generation can infer

A representative JSON value reveals property names, observed primitive types, nested objects and arrays. A generator can turn that shape into readable interfaces quickly, which is useful when exploring an unfamiliar API.

It cannot know every allowed variation. Generated types are a starting point, not authoritative API documentation.

One sample hides optional properties

A field present in one example may be absent elsewhere, and an omitted field may exist in another response variant. Compare multiple samples and the real API contract before deciding which properties are optional.

interface User {
  id: string;
  displayName?: string;
}

Null and undefined describe different states

JSON can contain null but cannot contain undefined. In TypeScript, an optional property can be absent, while a nullable property is present with null as an allowed value. Model those states deliberately.

Empty and mixed arrays need judgment

An empty array provides no evidence about its element type. Mixed arrays can imply a union, but they can also reveal inconsistent upstream data. Prefer the documented contract over accidental sample contents.

Prefer unknown when the shape is genuinely uncertain

any disables downstream type checking. unknown forces code to narrow or validate before use and is a safer representation when the sample does not reveal enough information.

Compile-time types do not validate runtime JSON

TypeScript types disappear after compilation. A server can still send unexpected data at runtime, so validate untrusted external data at the application boundary when correctness matters.

  • Use representative samples.
  • Review optional and nullable fields.
  • Rename reusable nested models clearly.
  • Avoid any when uncertainty should be explicit.
  • Add runtime validation separately.

Common questions

Frequently asked questions

Do TypeScript interfaces validate JSON at runtime?

No. Interfaces provide compile-time checking only. External JSON still needs runtime validation when trust or correctness matters.

Why did the generator choose unknown or a broad type?

The sample may not contain enough information, especially for empty arrays, nulls or inconsistent records.

Should a field be optional because one sample omitted it?

Not automatically. Use multiple samples and the actual API contract to determine whether omission is permitted.