datapry

JSON to TypeScript

Generate TypeScript interfaces from JSON samples, with optional and nullable fields inferred. Runs in your browser, so nothing is uploaded.

Declare as

JSON sample

TypeScript

Waiting for input

About this tool

Paste an API response and get TypeScript types for it. When the JSON is an array, every item is merged into one type, so a field missing from some items becomes optional and a field that's sometimes null becomes nullable. Nested objects get their own named interfaces.

How to use it

  1. Paste a JSON sample. More samples give more accurate types.
  2. Set the root name and choose interface or type, export and readonly.
  3. Copy the TypeScript into your project.

Example

Input
[{"id":1,"name":"Alex","manager":null},{"id":2,"name":"Riya","email":"riya@example.com","manager":{"id":1}}]
Output
export type Root = RootItem[];

export interface RootItem {
  id: number;
  name: string;
  manager: Manager | null;
  email?: string;
}

export interface Manager {
  id: number;
}

email is optional because only one item has it, and manager is nullable because it's null in one item.

Questions

How are optional fields detected?
A field that's missing from some objects in the same array is marked optional with ?. The more samples you paste, the more accurate this gets.
What about empty arrays?
An array that's empty in every sample is typed unknown[], since there's nothing to infer from. Add a sample with items to get a precise type.
Can it handle keys with spaces or dashes?
Yes. Keys that aren't valid identifiers are quoted, as in "first name": string.