UNPKG

ts-schema-factory

Version:

Generate TypeScript interfaces from database query results or JS arrays

83 lines (58 loc) 1.75 kB
# ts-schema-factory Generate TypeScript interfaces from database query results or JavaScript arrays automatically. ## Installation ```bash npm install ts-schema-factory ``` ## Usage ### From JavaScript Array ```javascript const { generateInterfaceFromArray } = require('ts-schema-factory'); const rows = [ { id: 1, name: 'Alice', age: 30 }, { id: 2, name: 'Bob', age: null }, { id: 3, name: 'Charlie', active: true, notes: 'Hello' } ]; // Generate TypeScript interface and save to User.ts const tsInterface = generateInterfaceFromArray(rows, 'User', 'User.ts'); // Print interface to console console.log(tsInterface); ``` ### Output ```typescript interface User { id: number; name: string; age?: number | null; active?: boolean | null; notes?: string | null; } ``` ### Optional: Save to File Pass the third argument as a filename, e.g., `'User.ts'`. The interface will be written to that file automatically. ## API ### `generateInterfaceFromArray(dataArray, interfaceName, outputFile?)` * **dataArray**: Array of objects (like database query results) * **interfaceName**: Name of the TypeScript interface to generate * **outputFile** *(optional)*: Path to save the interface as a `.ts` file * **Returns**: The generated TypeScript interface as a string ## Example ```javascript const { generateInterfaceFromArray } = require('ts-schema-factory'); const data = [ { id: 1, title: 'Book 1', price: 9.99 }, { id: 2, title: 'Book 2', price: 12.5, description: 'A great book' } ]; generateInterfaceFromArray(data, 'Book', 'Book.ts'); ``` This will create a file `Book.ts` with: ```typescript interface Book { id: number; title: string; price: number; description?: string | null; } ``` ## License MIT