How to generate TypeScript types from JSON
Short answer
Take a representative JSON sample and convert each object into a TypeScript interface, mapping its keys to typed fields. This gives you autocomplete and compile-time checks, though you should review optional fields and unions afterward.
Why type your JSON
When data arrives as untyped JSON, the compiler cannot catch a misspelled field or a wrong type. Describing the shape with TypeScript interfaces turns those runtime surprises into compile-time errors and unlocks editor autocomplete.
{ "id": 42, "name": "Ada", "active": true }
interface User {
id: number;
name: string;
active: boolean;
}What to review by hand
- Optional fields: a sample may omit keys that are sometimes present, so mark them with
? - Unions: a field that is sometimes null or different types needs a union like
string | null - Empty arrays: the generator cannot infer an element type from
[] - Names: generated interface names may need renaming to match your domain