json.cihat.dev

JSON to TypeScript

Paste an API response and get TypeScript interfaces for it, with nested types named after their keys.

Declare as

How to use it

  1. Paste a JSON sample, ideally a real response with several items in each array. A sample is loaded.
  2. Name the root type, and choose interface or type.
  3. Keep optional on so a key that appears in only some array items gets a ?.
  4. Copy the result into your code or download types.ts.

How the types are worked out

Every item of an array is read, not only the first, and their shapes are merged: a key present in every item is required, a key present in some is optional, and a key whose values differ in type gets a union such as string | null. Nested objects become their own interfaces named after their key in PascalCase; items of an array named repos become Repo.

An empty array is typed unknown[], because an empty sample says nothing about its items. A value that is null in every item is typed null; widen it by hand once you know what it holds.

A sample is not a schema

The types describe the JSON you paste, nothing more. A field that is a number in your sample may be a string in another response, and a field that never appeared is not in the types at all. Paste a response that covers the cases you handle, and treat the result as a starting point to review.

Questions people ask

Is my JSON uploaded?

No. The types are generated in your browser; nothing is sent to a server.

Should I use interface or type?

Both work for object shapes. Interfaces can be extended and merged; type aliases can also name unions. Many codebases pick one and stick to it.

Why is a field marked optional?

Because at least one item in the same array does not have it. Turn the option off to make every key required.

Does it handle keys with spaces or dashes?

Yes. Keys that are not valid identifiers are written in quotes, such as "first-name": string.