JSON to TypeScript Interface Converter

2.1.0 · active · verified Sun Apr 19

json-to-ts is a utility library, currently at stable version 2.1.0, designed to automatically convert JSON objects into corresponding TypeScript interface definitions. It parses input JSON data, intelligently inferring primitive types (strings, numbers, booleans), array structures, and nested objects. Key differentiators include its robust handling of complex scenarios like automatic array type merging, generation of union types where data properties might vary, and prevention of redundant type declarations, ensuring clean and efficient output. It also offers the capability to infer optional properties. This package aims to streamline the developer workflow by reducing the manual effort and potential for errors associated with defining TypeScript types for API responses or dynamic data structures. It follows an active release cadence, providing reliable tooling for TypeScript projects dealing with structured JSON.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to import and use `json-to-ts` to convert a complex JSON object into a set of TypeScript interfaces, including nested objects and optional properties.

import JsonToTS from 'json-to-ts';

const json = {
  users: [
    { id: 1, name: 'Alice', email: 'alice@example.com' },
    { id: 2, name: 'Bob', email: 'bob@example.com', phone: '123-456-7890' }
  ],
  settings: {
    theme: 'dark',
    notificationsEnabled: true
  },
  version: 2.1,
  timestamp: new Date().toISOString()
};

console.log('Generating TypeScript interfaces...');
JsonToTS(json, {
  rootName: 'AppData',
  // Optional: customize type names, e.g., for arrays of specific objects
  // arrayTypeSuffix: 'Item'
}).forEach(typeInterface => {
  console.log(typeInterface);
});
/* Expected Output:
interface AppData {
  users: User[];
  settings: Settings;
  version: number;
  timestamp: string;
}
interface User {
  id: number;
  name: string;
  email: string;
  phone?: string;
}
interface Settings {
  theme: string;
  notificationsEnabled: boolean;
}
*/

view raw JSON →