Dev tools

JSON to TypeScript

JSON to TypeScript. Infers types from an example JSON document. Nested objects become named types by their key; mixed-type arrays fall back to a broad/any type. Runs on your device.

Runs on your device. The file is never uploaded.

JSON to TypeScript reads one example document and prints an interface for every object in it. The outermost interface is called Root, nested ones take the name of the key above them, and a key that is not a valid identifier is quoted. Two objects sharing a key name give two interfaces with one name.

Input

Questions

What does the output look like?

Plain interface declarations, one per object found in your document. The top-level type is called Root and nested objects are named after the key that holds them, capitalised. Types are printed depth first with the root last, so nested interfaces are declared before the ones that reference them.

How do JSON types map to TypeScript?

Strings become string, booleans become boolean, and every number becomes number, whole or not. An array becomes T[] where T comes from its first element. A null becomes the literal type null, and an empty array becomes unknown[], since there is no element to learn from.

Are any fields marked optional?

No. Every key in the example becomes a required property with no question mark, because the tool sees one document and cannot tell which fields might be absent. Add the question marks yourself afterwards, along with any union types for fields that hold more than one shape. Generating from an example that shows the minimum shape gets you closer.

What happens with mixed or ragged arrays?

Only the first element is inspected. An array whose entries have different shapes is typed from entry zero, so later entries might not satisfy the generated interface. Reorder the example so the fullest object comes first, or widen the type by hand.

Why did it refuse my file?

If the document has no object anywhere at the top level, there is nothing to name a type after and the tool stops with "top-level value has no object fields to name a type after". A JSON file holding a bare string, a number or an array of numbers hits this. Wrap the value in an object and run it again.

Can two generated interfaces end up with the same name?

Yes. Names come from the key, so two objects that live under the same key name in different parts of the document produce two interfaces with the same name and different bodies. Rename one before you paste the result into a project.

Related Dev tools