How to Convert JSON to TypeScript

A JSON sample can speed up defining the types for an API integration. Use it as evidence about one observed response, then refine the generated type against documentation and additional fixtures. A separate runtime check protects the boundary where data enters your program.

Generate a draft from one representative payload

Paste this payload into JSON to TypeScript and generate the editable Root type. The nested object becomes a nested type and the tags array becomes a string array. Rename Root to something tied to the endpoint, such as DeploymentResponse, and keep the example close to its tests.

A generator can infer primitive types, but it cannot infer that state is restricted to two values. Check the contract before narrowing it. If the API explicitly documents running and stopped, use a literal union rather than guessing from a single response.

JSON
{"id":"deploy-42","state":"running","labels":{"team":"ops"},"tags":["staging"]}

Model missing values and empty arrays

If labels may be absent, mark it optional. If it is always present but can be null, use a union with null. Those choices affect the checks callers must perform before accessing team. Keep them distinct when the API treats them differently.

An empty array cannot tell a generator the allowed element type. Start from the item definition in your schema or use a fixture with at least one item. Mixed arrays may lead to a wide union. A discriminated union is easier to use when each variant has a predictable state or kind field and a different set of required properties.

TypeScript
type DeploymentResponse = {
  id: string;
  state: "running" | "stopped";
  labels?: { team: string };
  tags: string[];
};

Keep runtime checks at the network boundary

Assign the result of JSON parsing to unknown and validate it with a runtime schema or explicit type guard before using it. A cast such as response as DeploymentResponse changes what the compiler assumes. It cannot stop a server from returning an error envelope or incorrect value.

Run fixtures through the same parser that production uses. Include an unexpected enum value, a missing required ID and a null labels value if your contract rejects null. Decide whether you want to reject additional fields or allow them for forward compatibility.

Frequently asked questions

Should I use an interface or type alias?
Either can describe a simple object. A type alias also expresses unions directly. Follow the conventions of the consuming codebase.
Does an ISO date string become Date?
A JSON date remains a string until application code validates and parses it. Model the wire format as a string.

Try it with these tools

Related developer guides