Generate TypeScript types from a JSON API example
JSON to TypeScript infers type declarations from a sample response. It gives frontend code a starting shape for objects, arrays, and their nested properties.
When should you use it?
- Type an API response in a TypeScript client.
- Create an interface for a JSON fixture.
- Spot fields whose sample values have inconsistent types.
Example: infer TypeScript fields from JSON
This abbreviated example shows the inferred name and active fields in TypeScript. The full generated file includes imports and helpers and may change with generator versions; review it before adding it to a project.
{"name":"Alex","active":true}export interface Root {
name: string;
active: boolean;
}An interface describes data at compile time
The generator infers fields and nested types from the sample you provide. That can save time when starting a client for an unfamiliar API. A TypeScript interface alone does not validate a network response at runtime, so a type assertion cannot prove that a server sent the promised shape. Use a runtime validator at the boundary when the application depends on those guarantees.
Review optional fields and representative variants
One successful response may omit error fields, nullable values, or alternative shapes. Include representative records in a sample array where possible, then compare inferred optionality with the real API contract. Keep large numeric identifiers as strings when JavaScript precision cannot represent them. Review the complete generated helpers and naming before incorporating the output into your project.
How do I generate a TypeScript interface from a sample JSON response?
Paste a representative response and generate TypeScript source. The inferred interface names fields and types observed in that sample; the full output may also include parsing helpers. Compare several real responses before deciding which fields are optional or nullable.
Illustrative TypeScript interface
typescriptexport interface Root {
id: number;
name: string;
active: boolean;
}This model fits {"id":7,"name":"Alex","active":true}. It is an illustration; inspect the downloaded .ts file for the generator’s exact names and helpers.
Does a TypeScript type validate the API response at runtime?
A declaration alone does not. The generated file may include conversion helpers, but review their behavior and use a runtime contract when untrusted API input must be checked.
What should you check before using the result?
Review optionality, unions, nulls, names, and runtime validation separately. A TypeScript declaration cannot prove an API will keep the same shape.
Understand JSON syntaxTechnical reference: quicktype model generation documentation