arrow_backBack to Blog

JSON to TypeScript: Generate Type-Safe Interfaces Automatically

schedule4 min read

TypeScript adds type safety to JavaScript, but defining types for JSON API responses by hand is tedious and error-prone. This guide shows you how to convert JSON into TypeScript interfaces efficiently, so you get full autocomplete and compile-time checks without the manual work.

Why Convert JSON to TypeScript

When you fetch data from an API, TypeScript does not know the shape of the response. Without types, you lose:

  • Autocomplete in your editor
  • Compile-time error checking
  • Safe refactoring
  • Self-documenting code

By defining TypeScript interfaces that match your JSON structure, you get all of these benefits. The question is how to create those interfaces without writing them by hand.

Manual Conversion

For simple JSON, you can write the interface yourself. Given this JSON:

{"name": "Alice", "age": 30, "email": "alice@example.com", "active": true}

The corresponding TypeScript interface is:

interface User { name: string; age: number; email: string; active: boolean; }

The mapping rules are straightforward:

  • JSON string → TypeScript string
  • JSON number → TypeScript number
  • JSON boolean → TypeScript boolean
  • JSON null → TypeScript null
  • JSON object → TypeScript nested interface
  • JSON array → TypeScript array with the item type

For nested objects and arrays, it gets more complex:

{"users": [{"name": "Alice", "tags": ["admin", "dev"]}]}

Becomes:

interface RootObject { users: User[]; }

interface User { name: string; tags: string[]; }

Manual conversion works for small structures but becomes impractical for large API responses with dozens of fields and nested objects.

Handling Optional Fields

API responses often include fields that may or may not be present. In TypeScript, you mark these with a question mark:

interface User { name: string; email?: string; phone?: string; }

If a field is sometimes null rather than absent, use a union type:

interface User { name: string; email: string | null; }

Deciding between optional (?) and nullable (| null) depends on whether the field is omitted entirely or explicitly set to null in the JSON.

Handling Union Types

Some JSON fields can be different types depending on context:

{"value": 42} {"value": "unknown"}

The TypeScript type for this is:

interface Data { value: string | number; }

Union types are common in real API responses. A conversion tool detects these automatically by analyzing multiple examples.

Using an Online Converter

An online JSON-to-TypeScript converter automates the entire process:

  1. Paste your JSON data into the input
  2. The tool analyzes the structure
  3. It generates TypeScript interfaces with correct types
  4. Copy the output into your project

This is the fastest way to handle large or complex JSON structures. A good converter handles:

  • Nested objects (generates separate interfaces)
  • Arrays of objects (infers the element type)
  • Optional fields (detects fields that are sometimes missing)
  • Union types (when a field has multiple possible types)
  • Mixed arrays (when array items have different shapes)

The JSONClean JSON to TypeScript converter does all of this in your browser. No data is sent to any server.

Generating Types from API Responses

For a more automated workflow, you can generate types directly from your API:

  1. Save a sample API response to a file
  2. Run it through a converter
  3. Import the generated types into your project
  4. Use them with your fetch calls

In your code:

const response = await fetch("/api/users"); const users: User[] = await response.json();

Now TypeScript knows the shape of users and will catch any incorrect property access at compile time.

Advanced: Generic API Types

For APIs that wrap responses in a standard envelope, you can use generics:

interface ApiResponse<T> { data: T; status: number; message: string; }

type UserResponse = ApiResponse<User>; type UsersResponse = ApiResponse<User[]>;

This pattern gives you type safety for the wrapper and the payload separately.

Best Practices

  1. **Generate from real data, not documentation** — the actual API response is the source of truth
  2. **Use interfaces, not types, for object shapes** — interfaces support declaration merging and are more idiomatic for object types
  3. **Mark optional fields explicitly** — do not make every field optional just to be safe
  4. **Name your interfaces meaningfully** — not RootObject or Interface1
  5. **Keep generated types in a dedicated file** — api-types.ts or similar
  6. **Regenerate when the API changes** — types that drift from reality are worse than no types at all

Try It Free

Ready to convert your JSON to TypeScript? Paste it into our free JSON to TypeScript converter and get clean, type-safe interfaces in seconds. Everything runs in your browser.

Frequently Asked Questions

Can TypeScript automatically infer types from JSON?

TypeScript can infer types from JSON imports using resolveJsonModule in tsconfig.json, but this creates inline types that are hard to reuse. For API responses parsed at runtime with JSON.parse, TypeScript infers the type as any. You need explicit interfaces or a converter tool to get proper typing.

Should I use interface or type for JSON objects?

Use interface for object shapes. Interfaces support declaration merging and extending, which is useful when your API types share common fields. Use type for unions, intersections, and utility types. Both work, but interface is the convention for data shapes in TypeScript.

How do I handle JSON fields that can be multiple types?

Use a TypeScript union type: field: string | number | null. A good JSON-to-TypeScript converter detects these cases by analyzing multiple JSON samples and generates the appropriate union types automatically.

build_circle

Try it yourself

Put what you learned into practice with our free json to typescript. 100% browser-side — your data never leaves your device.

open_in_newOpen JSON to TypeScript

Related Articles