JSON to TypeScript

JSON to TypeScript with optional fields

Real API data is rarely uniform: some objects leave a key out, and some send null. When you convert an array of objects, this tool merges every item into one type. A key that is missing from some items becomes optional with ?, and a key that is sometimes null gets | null.

The example below already has both cases. Edit it or paste your own JSON.

JSON to TypeScript
Style
InputValid JSONJSON

Press Command or Control plus Enter to run. Tab inserts indentation; press Escape, then Tab, to leave the editor.

Result
Your result will appear here.
Ready4 lines · 134 chars

Optional versus null

The difference matters when you read the value. user.email can be undefined, while user.nickname is either a string or null, so user.nickname ?? "Anonymous" handles both cases.

In the JSONIn TypeScriptMeaning
Key missing from some itemsemail?: stringThe property may not exist at all.
Key present, sometimes nullnickname: string | nullThe property always exists, but may be empty.
Bothnickname?: string | nullIt may be missing or null.

Give the generator enough samples

  • A key that appears in every sample is marked required. If your API sometimes omits it, include an item without it.
  • A key that is null in every sample is typed as just null. Include one item where it has a real value, so the type becomes string | null.
  • An empty array is typed unknown[]. Put at least one item in it.

Make every field optional

For a PATCH body or a form draft where any field may be left out, keep the generated interface and wrap it with Partial, rather than adding ? by hand:

type UserPatch = Partial<UserItem>;

async function updateUser(id: number, patch: UserPatch) {
  await fetch(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(patch) });
}

With exactOptionalPropertyTypes

If your tsconfig.json turns on exactOptionalPropertyTypes, email?: string means the key can be left out but can't be set to undefined. If your code sets optional keys to undefined, write email?: string | undefined instead.

Frequently asked questions

Should I use interface or type for JSON data?

Either works for describing JSON. Interfaces give clearer error messages and can be extended; type aliases can also describe unions. The tool can generate both.

Do generated types check the data at runtime?

No. TypeScript types disappear when the code is compiled. To check API responses at runtime, validate them with a schema library such as Zod or with a JSON Schema validator.

Why is a nested object in an array marked optional?

It was missing from at least one item in the array. Check the samples: if it really is always there, the input JSON is incomplete.

From the blog