UNPKG

@junaidatari/json2ts

Version:

Convert JSON objects to TypeScript interfaces automatically.

133 lines (132 loc) 4.84 kB
/** * @author Junaid Atari <mj.atari@gmail.com> * @copyright 2025 Junaid Atari * @see https://github.com/blacksmoke26 */ import ConverterBase from '../base/ConverterBase'; import type { ExportType, ConvertOptions } from '../typings/global'; /** * A utility class that converts JSON objects into flattened TypeScript interfaces. * This converter embeds all nested object properties into a single interface definition, * eliminating the need for separate interface definitions for nested structures. * * Key features: * - Converts JSON objects to TypeScript interfaces * - Embeds nested objects into the main interface * - Handles arrays and primitive types appropriately * - Prevents infinite recursion with circular reference detection * - Supports custom interface names and export types * * @example * Input JSON: * ```json * { * "user": { * "id": 1, * "name": "John Doe" * }, * "posts": [ * { "title": "First Post", "content": "Hello World" } * ] * } * ``` * * Generated TypeScript interface: * ```typescript * export interface RootObject { * user: { * id: number; * name: string; * }; * posts: { * title: string; * content: string; * }[]; * } * ``` */ export default class JsonToFlattenedTsConverter extends ConverterBase { private options; /** * Tracks visited objects during conversion to prevent infinite recursion * when circular references are encountered in the input JSON. * Uses WeakSet to avoid memory leaks for objects that are no longer referenced. */ private visitedObjects; /** * Creates an instance of JsonToFlattenedTsConverter. * @param options Configuration options for the conversion process. */ private constructor(); /** * Converts a JSON object or string into a flattened TypeScript interface. * * @param jsonData - The JSON data to convert. Can be an object or a JSON string. * @param interfaceName - Name for the generated interface. Defaults to 'RootObject'. * @param exportType - Type of export ('root' or 'interface'). Defaults to 'root'. * @param options Configuration options for the conversion process, including array * tuple size constraints and other conversion settings. * @returns The generated TypeScript interface as a string, or null if input is invalid. * * @example * ```typescript * const jsonData = { * user: { id: 1, name: "John" }, * posts: [{ title: "Hello", content: "World" }] * }; * const interfaceString = JsonToFlattenedTsConverter.convert(jsonData, "UserData"); * console.log(interfaceString); * // Output: * // export interface UserData { * // user: { * // id: number; * // name: string; * // }; * // posts: { * // title: string; * // content: string; * // }[]; * // } * ``` */ 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; /** * Generates the TypeScript interface code from parsed JSON data. * * @param jsonData - The parsed JSON object to convert. * @param interfaceName - Name for the generated interface. * @param exportType - Type of export ('root' or 'interface'). * @returns The complete TypeScript interface code. */ protected convertJson(jsonData: unknown, interfaceName: string, exportType?: ExportType): string; /** * Recursively generates TypeScript type definitions for objects and their properties. * Embeds nested objects into the current interface definition. * * @param obj - The object or value to convert to a TypeScript type. * @param indentLevel - Current indentation level for formatting the output. * @returns A string containing the TypeScript type definition. */ private generateObjectBody; /** * Determines the appropriate TypeScript type for a given value. * Delegates to generateObjectBody for complex types (objects and arrays). * * @param value - The value to analyze for type determination. * @param indentLevel - Current indentation level for formatting. * @returns The TypeScript type string for the given value. */ private getType; /** * Creates an indentation string based on the specified level. * Uses two spaces per indentation level for consistent formatting. * * @param level - The number of indentation levels. * @returns A string containing the appropriate number of spaces. */ private getIndent; }