← Back to Blog

Convert JSON to TypeScript: Types and Interfaces Guide

Learn to convert JSON to TypeScript types and interfaces. Covers tools, best practices, and runtime validation with Zod.

Big JSON Team11 min readprogramming
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

11 min read

Why Convert JSON to TypeScript?

TypeScript types provide compile-time safety and better developer experience with autocomplete and error detection.

Quick Example

JSON Data

{

"id": 1,

"name": "Alice",

"email": "alice@example.com",

"active": true

}

TypeScript Interface

interface User {

id: number;

name: string;

email: string;

active: boolean;

}

Online Tools

  • Paste JSON
  • Select TypeScript
  • Copy generated types
  • Options:

    • Interface vs Type
    • Optional properties
    • Runtime validation

    Type Mapping

    | JSON Type | TypeScript Type |

    |-----------|-----------------|

    | string | string |

    | number | number |

    | true/false | boolean |

    | null | null |

    | array | T[] or Array |

    | object | interface or type |

    Handling Optional and Null

    interface User {
    

    name: string;

    middleName?: string; // Optional

    deletedAt: string | null; // Nullable

    nickname?: string | null; // Both

    }

    Arrays and Nested Objects

    interface Response {
    

    users: User[];

    metadata: {

    total: number;

    page: number;

    };

    }

    Using quicktype CLI

    # Install
    

    npm install -g quicktype

    # Generate types

    quicktype -s json -o types.ts data.json

    # From URL

    quicktype -s json -o types.ts "https://api.example.com/users"

    Runtime Validation with Zod

    import { z } from 'zod';
    
    

    const UserSchema = z.object({

    id: z.number(),

    name: z.string(),

    email: z.string().email(),

    active: z.boolean()

    });

    // Infer TypeScript type

    type User = z.infer<typeof UserSchema>;

    // Validate at runtime

    const result = UserSchema.safeParse(data);

    if (result.success) {

    const user: User = result.data;

    }

    Complex Types

    Union Types

    type Status = "pending" | "approved" | "rejected";
    
    

    interface Task {

    id: number;

    status: Status;

    }

    Generic Types

    interface ApiResponse<T> {
    

    data: T;

    error?: string;

    }

    type UserResponse = ApiResponse<User>;

    Type vs Interface

    Use Interface for:

    • Object shapes
    • Extending/inheritance
    • Public APIs

    Use Type for:

    • Unions
    • Complex types
    • Function types

    Best Practices

  • Use quicktype for initial conversion
  • Refine types manually
  • Add runtime validation with Zod
  • Keep types close to usage
  • Export types properly
  • Automated Workflow

    // schema.ts
    

    export const schemas = {

    user: z.object({

    id: z.number(),

    name: z.string()

    })

    };

    export type User = z.infer<typeof schemas.user>;

    // api.ts

    import { schemas, User } from './schema';

    async function getUser(id: number): Promise<User> {

    const response = await fetch(/api/users/${id});

    const data = await response.json();

    return schemas.user.parse(data);

    }

    Conclusion

    Converting JSON to TypeScript types improves code quality and developer experience. Use quicktype for generation and Zod for runtime validation!

    Share:

    Related Articles

    Read in other languages