@junaidatari/json2ts
Version:
Convert JSON objects to TypeScript interfaces automatically.
150 lines (149 loc) • 5.95 kB
TypeScript
/**
* @author Junaid Atari <mj.atari@gmail.com>
* @copyright 2025 Junaid Atari
* @see https://github.com/blacksmoke26
*/
import ConverterBase from '../base/ConverterBase';
import type { ConvertOptions, ExportType } from '../typings/global';
/**
* Converts JSON data into TypeScript interface definitions with advanced type inference.
*
* This class provides comprehensive functionality to analyze JSON objects and generate
* corresponding TypeScript interface definitions with intelligent type detection.
* It supports nested objects, arrays, primitive types, and handles circular references
* to prevent infinite recursion.
*
* Key Features:
* - Intelligent interface naming based on object keys and structure
* - Full support for nested objects and arrays
* - Circular reference detection to prevent infinite loops
* - Flexible export modes (root, all, none) for different use cases
* - Automatic type inference for JSON primitives
* - Advanced array type detection with tuple types for mixed arrays
* - Configurable array tuple size limits for optimal type representation
* - Strict type checking mode for more precise type inference
* - Custom type mapping for overriding default type detection
*
* @example
* ```typescript
* const json = {
* name: "John",
* age: 30,
* isActive: true,
* address: {
* street: "123 Main St",
* city: "New York",
* coordinates: [40.7128, -74.0060]
* },
* tags: ["user", "active", 2025]
* };
* const tsInterface = JsonToTsConverter.convert(json, "User", "root", {
* arrayMaxTupleSize: 5,
* arrayMinTupleSize: 2,
* strict: true,
* typeMap: {
* 'timestamp': 'Date',
* 'uuid': 'string'
* }
* });
* console.log(tsInterface);
* ```
*/
export default class JsonToTsConverter extends ConverterBase {
private options;
/**
* Cache storing generated TypeScript interface definitions.
*
* Maps interface names to their complete definition strings. This prevents duplicate
* interface generation and maintains proper dependency ordering when assembling
* the final output.
*/
private interfaces;
/**
* Tracks visited objects to detect circular references.
*
* Uses WeakSet to avoid memory leaks while preventing infinite recursion
* when objects reference themselves or create circular dependencies.
*/
private visitedObjects;
/**
* Creates an instance of JsonToTsConverter.
* @param options Configuration options for the conversion process.
*/
private constructor();
/**
* Converts JSON data into TypeScript interface strings.
*
* Static entry point that parses input JSON and generates corresponding
* TypeScript interfaces. Supports both object and string inputs.
*
* @param jsonData - JSON object or string to convert
* @param interfaceName - Name for the root interface (default: 'RootObject')
* @param exportType - Export mode: 'root', 'all', or 'none' (default: 'root')
* @param options - Configuration options for the conversion process
* @returns Generated TypeScript interface string or null if parsing fails
*
* @example
* ```typescript
* const result = JsonToTsConverter.convert(
* '{"name": "John", "age": 30}',
* 'Person',
* 'all',
* { arrayMaxTupleSize: 5, arrayMinTupleSize: 2, strict: true }
* );
* ```
*/
static convert(jsonData: unknown | string, interfaceName?: string, exportType?: ExportType, options?: ConvertOptions): string | null;
/**
* Factory method to create converter instance.
*/
protected static createConverter(options: ConvertOptions): ConverterBase;
/**
* Core conversion method that processes parsed JSON data.
*
* Handles the main conversion logic, including initialization,
* interface generation, and final assembly of the output string.
*
* @param jsonData - Parsed JSON object to convert
* @param rootInterfaceName - Name for the root interface
* @param exportType - Export mode configuration
* @returns Complete TypeScript interface definitions
*/
protected convertJson(jsonData: unknown, rootInterfaceName: string, exportType?: ExportType): string;
/**
* Recursively generates interface definition for an object.
*
* Analyzes object structure and creates TypeScript interface matching its properties.
* Handles nested objects recursively and tracks visited objects to prevent
* infinite recursion with circular references.
*
* @param obj - Object to convert to interface
* @param interfaceName - Name for the generated interface
* @param appendExport - Whether to include export keyword
*/
private generateInterface;
/**
* Determines TypeScript type string for a given value with comprehensive type inference.
*
* Analyzes value and returns appropriate TypeScript type with support for all JavaScript types
* including primitives, complex objects, built-in classes, and special types like Date, RegExp,
* Error, Promise, Generator, Function, and collections (Set, Map, WeakMap, WeakSet). Also handles
* typed arrays, ArrayBuffer, DataView, Symbols, BigInt, and class instances.
*
* @param value - Value to analyze
* @param parentKey - Property key used for naming child interfaces
* @param appendExport - Whether child interfaces should be exported
* @returns TypeScript type string representation
*/
private getType;
/**
* Sanitizes and capitalizes string for interface naming.
*
* Converts JSON keys into valid TypeScript interface names by removing
* invalid characters and capitalizing the first letter.
*
* @param str - String to process
* @returns Sanitized string suitable for interface names
*/
private capitalize;
}