How to generate TypeScript from JSON
- Paste a JSON example. The more items its arrays contain, the better optional fields and unions are detected.
- Set the name of the root type and choose
interfaceortype, with or withoutexportandreadonly. - Copy the TypeScript code into your project or download it as a
.tsfile.
How TypeScript types are inferred from JSON
| JSON | TypeScript |
|---|---|
"Ada" | string |
42, 3.14 | number |
true | boolean |
null next to other values | a union such as string | null |
"address": {"city": "Paris"} | a separate interface Address |
"users": [{"id": 1}] | User[] – the item name is made singular |
| a key missing in some array items | an optional property key?: |
[1, "a"] | (string | number)[] |
[] | unknown[] |
{} | Record<string, unknown> |
Example
The JSON {"id": 1, "name": "Ada", "tags": ["admin"], "manager": null} becomes:
export interface Root { id: number; name: string; tags: string[]; manager: null; }
Rename Root to something meaningful such as User or ApiResponse. Nested objects with exactly the same shape – a billing and a shipping address, for example – share one interface, and keys that are not valid identifiers are quoted, e.g. "first-name": string.
Frequently asked questions
Interface or type – which should I choose?
For object shapes both behave the same. Interfaces can be extended and merged, while type aliases can also describe unions. Many teams use interfaces for objects; follow the style of your codebase.
How are optional fields detected?
Objects inside the same array are merged. A key that is missing in some of them becomes optional (key?:), and a key with different value types becomes a union.
Does this validate data at runtime?
No. TypeScript types disappear when the code runs. To check incoming data, generate a JSON Schema from the same example with our JSON Schema generator and validate against it with a schema library.
Is my JSON sent to a server?
No. The types are generated in your browser, so you can safely paste private API responses.