JSON to TypeScript Interface Converter
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
-
Cannot find module 'json-to-ts'
cause The package is not installed or the import path is incorrect.fixRun `npm install json-to-ts` or `yarn add json-to-ts`. Verify the import statement uses the correct package name: `from 'json-to-ts'`. -
TypeError: JsonToTS is not a function
cause The main conversion function was imported incorrectly, often by attempting a named import from a module that uses a default or CommonJS module.exports export.fixFor CommonJS, use `const JsonToTS = require('json-to-ts');`. For ESM, use `import JsonToTS from 'json-to-ts';` to correctly capture the default export. -
Property 'x' is missing in type 'Y' but required in type 'Z' (or similar type mismatch during compilation/runtime)
cause The TypeScript interfaces generated by `json-to-ts` do not perfectly align with the actual runtime JSON data, possibly due to optional fields not being inferred correctly or unexpected variations in data structure.fixManually review and adjust the generated TypeScript interfaces to precisely reflect the expected JSON structure. Add `?` for optional properties or use union types (e.g., `string | number | null | undefined`) where data can vary. Ensure sample JSON provided for generation is representative of all possible data shapes.
Warnings
- gotcha Generating types for very large or deeply nested JSON structures can strain TypeScript's type inference engine, potentially leading to slow compilation times or 'Type instantiation is excessively deep and potentially infinite' errors, particularly with older TypeScript versions or specific compiler flags.
- gotcha While `json-to-ts` excels at inference, highly ambiguous JSON structures (e.g., arrays with mixed types, objects with inconsistent property presence across array elements, or null values without explicit alternatives) might result in broader union types or `any` where more specific types were desired. This sometimes requires manual refinement of the generated interfaces.
- gotcha The library primarily uses a CommonJS default export (`module.exports = function`). When used in a pure ESM project, especially with strict `esModuleInterop: false` or certain bundler configurations, directly importing `JsonToTS` might behave unexpectedly if not using `import JsonToTS from 'json-to-ts'` (default import syntax).
Install
-
npm install json-to-ts -
yarn add json-to-ts -
pnpm add json-to-ts
Imports
- JsonToTS
import { JsonToTS } from 'json-to-ts';import JsonToTS from 'json-to-ts';
- JsonToTS (CommonJS)
const JsonToTS = require('json-to-ts'); - Type definitions
import type { RootObject, Cat } from 'json-to-ts/dist/types';
Quickstart
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;
}
*/