DevToolBoxGRATIS
Blog

JSON naar TypeScript: Complete gids met voorbeelden

12 min lezenby DevToolBox

Converting JSON to TypeScript interfaces is one of the most common tasks in modern web development. Whether you're consuming REST APIs, working with configuration files, or defining data models, having proper TypeScript types ensures type safety and better developer experience.

Convert JSON to TypeScript instantly with our free tool β†’

Why Convert JSON to TypeScript?

TypeScript's type system catches errors at compile time that would otherwise surface at runtime. When you receive JSON from an API, TypeScript has no idea what shape that data takes β€” unless you define interfaces. Without types, you lose autocompletion, refactoring support, and compile-time error checking.

  • Autocompletion β€” your editor suggests valid property names
  • Compile-time errors β€” catch typos and missing fields before deployment
  • Self-documenting code β€” interfaces describe your data shape
  • Refactoring safety β€” rename a field and TypeScript finds every usage

Basic Conversion Rules

The fundamental mappings from JSON types to TypeScript types are straightforward:

JSON TypeTypeScript TypeExample
stringstring"hello"
number (int)number42
number (float)number3.14
booleanbooleantrue
nullnullnull
arrayT[][1, 2, 3]
objectinterface{"key": "val"}
// JSON
{
  "name": "Alice",
  "age": 30,
  "active": true
}

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

Handling Nested Objects

Real-world JSON is rarely flat. When objects contain other objects, you should create separate interfaces for each level:

// JSON
{
  "id": 1,
  "name": "Alice",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "coordinates": {
      "lat": 39.7817,
      "lng": -89.6501
    }
  }
}

// TypeScript
interface Coordinates {
  lat: number;
  lng: number;
}

interface Address {
  street: string;
  city: string;
  coordinates: Coordinates;
}

interface User {
  id: number;
  name: string;
  address: Address;
}

Tip: Use separate interfaces rather than deeply nested inline types. It makes your code more readable and reusable.

Array Types

Arrays in JSON can contain uniform or mixed types. TypeScript handles both cases:

// Uniform array
{ "tags": ["typescript", "react", "next"] }
// -> tags: string[]

// Array of objects
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ]
}
// -> users: User[]

// Mixed array (rare but possible)
{ "data": [1, "two", true] }
// -> data: (number | string | boolean)[]

When an array contains objects of the same shape, define a dedicated interface. For heterogeneous arrays, use union types.

Null and Optional Fields

JSON APIs often return null for missing values, or omit fields entirely. TypeScript distinguishes between these two cases:

// JSON with null values
{
  "id": 1,
  "name": "Alice",
  "avatar": null,
  "bio": null
}

// TypeScript β€” nullable vs optional
interface User {
  id: number;
  name: string;
  avatar: string | null;    // field exists, value can be null
  bio?: string;              // field might not exist at all
  nickname?: string | null;  // might not exist OR might be null
}

Key difference: null means the field exists but has no value. undefined (optional with ?) means the field might not be present at all. Use | null for nullable fields and ? for optional fields.

Best Practices

  • Use interface over type for object shapes β€” interfaces are extendable and produce better error messages
  • Prefer readonly for data from APIs that you don't intend to mutate
  • Use unknown instead of any for truly dynamic fields β€” it forces you to validate before use
  • Name interfaces clearly β€” use User, not IUser or UserInterface
  • Export shared interfaces in a central types/ directory for reuse across your project
  • Validate at runtime β€” TypeScript types disappear at runtime, so use libraries like Zod or io-ts for API boundary validation
// Good: runtime validation with Zod
import { z } from 'zod';

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  avatar: z.string().nullable(),
});

type User = z.infer<typeof UserSchema>;

// Validate API response
const user = UserSchema.parse(await res.json());

Automate the Conversion

Manually writing interfaces for large JSON payloads is tedious and error-prone. Use our JSON to TypeScript converter to instantly generate accurate interfaces from any JSON input. Paste your JSON, get TypeScript β€” it's that simple.

Try the JSON to TypeScript converter now β†’

𝕏 Twitterin LinkedIn
Was dit nuttig?

Blijf op de hoogte

Ontvang wekelijkse dev-tips en nieuwe tools.

Geen spam. Altijd opzegbaar.

Try These Related Tools

TSJSON to TypeScript{ }JSON FormatterGoJSON to Go StructZDJSON to Zod Schema

Related Articles

JSON naar Go Struct: Mapping-strategieΓ«n en best practices

Beheers JSON naar Go struct-conversie. Struct tags, geneste types, omitempty, aangepaste marshaling en praktijkpatronen.

TypeScript vs JavaScript: Wanneer en hoe te converteren

Praktische gids over wanneer TypeScript naar JavaScript te converteren en andersom. MigratiestrategieΓ«n, tooling, bundelgrootte-impact en teamoverwegingen.

JSON Schema Validatie: Typen, tools en best practices

Alles over JSON Schema-validatie: van basistypes tot geavanceerde patronen, validatiebibliotheken en integratie met TypeScript en API's.

JSON naar Java-klasse Converter: POJO, Jackson, Gson & Lombok Gids

Converteer JSON naar Java-klasse online. Genereer POJO met Jackson, Gson en Lombok met codevoorbeelden.

JSON to Zod Schema: Type-Safe Runtime Validation in TypeScript

Learn how to convert JSON to Zod schemas for type-safe runtime validation in TypeScript. Covers basic types, objects, arrays, unions, z.infer, and comparison with JSON Schema.