How to use the JSON to TypeScript Interface Generator
- Paste JSON into the left box, or click Load sample.
- Set the Root name, and choose interface or type.
- Tick Optional (?) when missing to mark keys that don't appear in every array item, or readonly for immutable data.
- Click Copy and paste the types into your project.
How the types are inferred
- Primitives: strings, numbers and booleans become
string,numberandboolean. Anullvalue becomesnull, 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 becomeunknown[]. - 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
itemsbecomesItemandcategoriesbecomesCategory. 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.