curly{bits}

curlybits / JSON to TypeScript

JSON to TypeScript Interface Generator

Paste an API response or any JSON, and get ready-to-use TypeScript interfaces as you type. Array items are merged so every field is covered, keys that some items lack become optional, and nested objects get their own named types.

Input JSON
TypeScript

      

How to use the JSON to TypeScript Interface Generator

  1. Paste JSON into the left box, or click Load sample.
  2. Set the Root name, and choose interface or type.
  3. Tick Optional (?) when missing to mark keys that don't appear in every array item, or readonly for immutable data.
  4. Click Copy and paste the types into your project.

How the types are inferred

  • Primitives: strings, numbers and booleans become string, number and boolean. A null value becomes null, joined with the other types the key takes.
  • Arrays: every item is looked at, not just the first, so [1, "a"] becomes (number | string)[], and objects in an array are merged into one interface. Empty arrays become unknown[].
  • Optional fields: a key that appears in some array items but not others is marked with ?.
  • Names: nested types are named after their key in PascalCase, and array items get the singular form, so items becomes Item and categories becomes Category. Objects with exactly the same shape share one type.
  • Odd keys: keys that aren't valid identifiers, like "first-name" or "123", are quoted.

Interface or type?

For plain object shapes they work almost the same. Interfaces can be extended and merged later, and many style guides prefer them for object types. Type aliases are needed for unions and other non-object types, which is why a JSON array or a plain value at the top level always becomes a type.

Check the result

Types are only as good as the sample. A field that's always a number in your sample might sometimes be null in real data, and a field that's always present might really be optional. Paste a few varied examples, for instance a JSON array of several responses, to get more accurate types.

Frequently asked questions

Why is a field typed as null?

Every value it had in your sample was null, so the real type couldn't be seen. Replace null with the expected type, such as string | null.

Does it detect dates?

No. Dates in JSON are strings, so they're typed as string. Convert them to Date in your code after parsing.

My JSON is invalid. What can I do?

Fix it with the JSON formatter, which repairs trailing commas, single quotes and comments.

Is my data uploaded?

No. The types are generated in your browser.

Add this JSON to TypeScript converter to your website

Free for blogs, schools and businesses. Copy the code below and paste it into your page's HTML. The tool works exactly like this one and runs in your visitors' browsers, so nothing is uploaded. Please keep the credit line so others can find it too.

Preview embed ↗