About the JSON to TypeScript
JSON to TypeScript reads a sample JSON payload and writes matching TypeScript interfaces, so you do not have to type out every field of an API response by hand. Nested objects become their own interfaces, and you choose the name of the root type.
How it works
The JSON is parsed and each property's value is examined. Strings, numbers, and booleans map to string, number, and boolean, and null maps to null. A nested object becomes a new interface named after its key in PascalCase, so an address key produces interface Address. Keys that are not valid identifiers, like first-name, are wrapped in quotes.
Arrays are typed from their first element: ["a", "b"] becomes string[], an array of objects becomes a named interface with [], and an empty array becomes unknown[]. If the top-level JSON is an array, the first item is used for the root interface and an extra type alias <Root>List = <Root>[] is added. Nested interfaces are printed before the root.
How to use
- 1
Enter a name for the top-level type in Root interface name, such as User.
- 2
Paste a representative JSON sample into the JSON input box.
- 3
Review the interfaces in Generated TypeScript; an error message appears if the JSON is invalid.
- 4
Click Copy TypeScript and paste the code into your project.
Worked examples
The sample object
A user record with a nested address.
A top-level array
An API that returns a list of products.
Frequently asked questions
Does this generate types for nested objects too?+
Yes. Each nested object gets its own interface, named after the key it was found under in PascalCase.
What happens if a field could be null?+
A field that is null in your sample is typed as null. If it can hold other values, change it by hand to a union such as string | null.
How are arrays typed?+
From their first element. [1, 2] becomes number[], an array of objects gets its own interface, and an empty array becomes unknown[].
Can I paste a JSON array at the top level?+
Yes. The first item is used to build the root interface, and a type alias such as RootList = Root[] is added for the whole array.
Why do I get an Invalid JSON error?+
The input must be strict JSON: double-quoted keys and strings, no trailing commas, and no comments. Fix the issue shown in the message, or run the data through a JSON validator first.