JSON to TypeScript

TypeScript types from a JSON sample.

Free tools that run in your browser. Nothing you type, open or create is uploaded to NerdBible or anyone else.

TypeScript

Types are inferred from the sample in your browser. Give it several items in an array when fields vary: the more realistic the sample, the more accurate the types. Nested objects get their own named interfaces, and identical shapes share one name.

How to use it

  1. Paste a JSON response or file. An array of several records gives the best result.
  2. Set the root name and choose interface or type, how null is handled and whether to export.
  3. Copy the TypeScript or download it as a .ts file.

Questions

How are optional fields found?

When a JSON array holds several objects, a field that is missing from some of them is marked optional with a question mark. A field that is present everywhere is required.

What happens when a field has different types?

The types are joined into a union, such as string | number. Arrays with mixed items become arrays of a union, written (string | number)[].

Should I use interface or type?

Either works for plain data shapes. Interfaces can be extended and merged, which suits public APIs; type aliases are needed for unions. Pick the one your codebase already uses.

Why is an empty array typed unknown[]?

An empty array says nothing about what it will hold. Replace unknown with the real item type, or add an example item to the sample.

About this tool

About JSON to TypeScript

Typing an API response by hand is tedious and easy to get wrong. Paste a sample of the JSON and this tool writes the TypeScript for you, ready to copy or download as a .ts file.

How types are inferred

  • Nested objects get their own named interfaces, and identical shapes share one name rather than being repeated.
  • When an array holds several objects, a field missing from some of them is marked optional with a question mark.
  • A field that holds different types in different records becomes a union, such as string | number.
  • An empty array becomes unknown[], because it says nothing about what it will hold.

Options

Set the name of the root type, choose interface or type alias, decide how null values are handled and whether each type is exported. Interfaces can be extended and merged, which suits public APIs; type aliases are needed for unions. Pick whichever your codebase already uses.

Getting accurate types

The output can only be as good as the sample. A single record cannot reveal which fields are optional, so paste an array of several realistic records, including ones with missing or null values. Then review the result: a field that happens to be a number in every sample might be a string ID in the API's documentation.

Types are generated in your browser; your data is not sent anywhere.

Related tools