JSON Schema to TypeScript Converter
This package facilitates the automatic conversion of JSON Schema definitions into TypeScript interfaces and types. It is currently at version 0.14.3 and appears to be actively maintained, with its last publish occurring four days ago as of the current date, indicating a relatively frequent release cadence. A key differentiator is its robust handling of standard JSON Schema features like `$ref` and `$defs` for modular schema definitions, and its ability to process arrays of defined types seamlessly into TypeScript arrays. Unlike some alternative tools that focus on generating JSON Schema *from* TypeScript code, this library specifically targets the generation of TypeScript *from* existing JSON Schema, providing a critical tool for schema-first development workflows. It operates with minimal dependencies and is part of the broader `constructive-io/dev-utils` monorepo, although it is designed for general-purpose use.
Common errors
-
TypeError: generateTypeScript is not a function
cause Attempting to import `generateTypeScript` using CommonJS `require()` syntax in an environment that expects ESM, or incorrect named/default export handling.fixEnsure you are using `import { generateTypeScript } from 'schema-typescript';` in an ESM-compatible environment (e.g., Node.js with `"type": "module"` in `package.json` or a bundler configured for ESM). -
Error: Invalid JSON Schema structure encountered
cause The input object passed to `generateTypeScript` is not a valid JSON Schema object, missing required properties, or contains syntax errors.fixValidate your JSON Schema against the JSON Schema specification (e.g., using `ajv` or an online validator) before passing it to the function. Ensure all required fields like `type` are present and correctly formatted. -
ReferenceError: Could not resolve schema reference '#/definitions/MyType'
cause The JSON Schema contains a `$ref` that points to a definition (`#/definitions/MyType` or an external file) that either does not exist, is misspelled, or cannot be accessed/resolved by the library's internal resolver.fixVerify that all `$ref` pointers are correct and that the referenced schemas are accessible. For external `$ref`s, ensure they are correctly provided to the library if it supports such options, or pre-resolve them if necessary.
Warnings
- gotcha The package is currently in a pre-1.0 version (0.14.3). While actively maintained, this implies that breaking changes could occur in minor versions, not just major ones, unlike libraries adhering to strict semver after 1.0. Review release notes carefully during upgrades.
- gotcha Complex or highly customized JSON Schema features, especially intricate `$ref` resolution across multiple files or non-standard keywords, might not be fully supported or could lead to unexpected TypeScript output.
- gotcha As part of the `constructive-io/dev-utils` monorepo, while functional as a standalone utility, there might be implicit assumptions or optimizations tailored for the broader `constructive-io` ecosystem. This generally does not affect direct usage, but advanced users integrating deeply might encounter subtle interactions.
Install
-
npm install schema-typescript -
yarn add schema-typescript -
pnpm add schema-typescript
Imports
- generateTypeScript
const generateTypeScript = require('schema-typescript');import { generateTypeScript } from 'schema-typescript';
Quickstart
import { generateTypeScript } from 'schema-typescript';
import * as fs from 'node:fs/promises';
const userSchema = {
"$id": "https://example.com/user.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User",
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"name": {
"type": "string",
"description": "Full name of the user"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"isActive": {
"type": "boolean",
"default": true
}
},
"required": ["id", "name", "email"]
};
async function generateUserTypes() {
try {
const tsDefinition = await generateTypeScript(userSchema, 'User');
await fs.writeFile('src/types/user.d.ts', tsDefinition);
console.log('TypeScript types for User generated successfully to src/types/user.d.ts');
console.log('\nGenerated TypeScript:\n', tsDefinition);
} catch (error) {
console.error('Failed to generate TypeScript types:', error);
}
}
generateUserTypes();