{"id":11174,"library":"json-schema-to-typescript","title":"JSON Schema to TypeScript","description":"json-schema-to-typescript is a utility that compiles JSON Schemas into TypeScript type declarations, enabling strong typing for data structures defined in JSON. Currently at version 15.0.4, it offers both a command-line interface (CLI) for file-based conversions and a programmatic API for integrating into build processes or applications. It is actively maintained with regular updates. Key differentiators include its robust handling of various JSON Schema features like `allOf`, `anyOf`, `oneOf`, `definitions`, and `$ref` for both local and external references. It aims to provide a reliable way to keep TypeScript types synchronized with JSON Schema definitions, reducing manual type creation and potential discrepancies between data contracts and application code. The library supports customizable options for output formatting, banner comments, and how `additionalProperties` are handled, which is crucial for controlling the strictness of generated types. It's particularly useful for projects consuming APIs or data where JSON Schema is the source of truth, facilitating a 'schema-first' development approach.","status":"active","version":"15.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/bcherny/json-schema-to-typescript","tags":["javascript","json","schema","typescript","compile","transpile","api","interface","typing"],"install":[{"cmd":"npm install json-schema-to-typescript","lang":"bash","label":"npm"},{"cmd":"yarn add json-schema-to-typescript","lang":"bash","label":"yarn"},{"cmd":"pnpm add json-schema-to-typescript","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses ES module imports. While `require` might work in some transpiled environments, `import` is the idiomatic and recommended way for modern Node.js and TypeScript projects.","wrong":"const { compile } = require('json-schema-to-typescript')","symbol":"compile","correct":"import { compile } from 'json-schema-to-typescript'"},{"note":"Used for reading JSON Schema directly from a file path. Ensure your project is configured for ES modules.","wrong":"const { compileFromFile } = require('json-schema-to-typescript')","symbol":"compileFromFile","correct":"import { compileFromFile } from 'json-schema-to-typescript'"},{"note":"This is a type-only import for the internal JSONSchema type used by the library, useful for strongly typing schema objects in your code. Use `import type` to ensure it's erased at runtime.","symbol":"JSONSchema","correct":"import type { JSONSchema } from 'json-schema-to-typescript'"}],"quickstart":{"code":"import { compile, Options } from 'json-schema-to-typescript';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nasync function generateTypes() {\n  const schemaPath = path.join(process.cwd(), 'schema.json');\n  const outputPath = path.join(process.cwd(), 'types.d.ts');\n\n  const mySchema = {\n    \"title\": \"UserProfile\",\n    \"description\": \"A schema for user profile data\",\n    \"type\": \"object\",\n    \"properties\": {\n      \"id\": { \"type\": \"string\", \"format\": \"uuid\" },\n      \"username\": { \"type\": \"string\", \"minLength\": 3, \"maxLength\": 20 },\n      \"email\": { \"type\": \"string\", \"format\": \"email\" },\n      \"age\": { \"type\": \"integer\", \"minimum\": 0, \"maximum\": 120 },\n      \"isActive\": { \"type\": \"boolean\", \"default\": true }\n    },\n    \"required\": [\"id\", \"username\", \"email\"]\n  };\n\n  // Save schema to a file for compileFromFile example (optional, but good for demo)\n  await fs.writeFile(schemaPath, JSON.stringify(mySchema, null, 2));\n\n  const options: Partial<Options> = {\n    bannerComment: \"/* eslint-disable */\\n/** Automatically generated from JSON Schema */\",\n    additionalProperties: false,\n    unreachableDefinitions: true\n  };\n\n  try {\n    // Example 1: Compile from an in-memory JS object\n    const tsFromObject = await compile(mySchema, 'UserProfile', options);\n    console.log('Generated from object:\\n', tsFromObject);\n\n    // Example 2: Compile from a file\n    const tsFromFile = await compileFromFile(schemaPath, options);\n    await fs.writeFile(outputPath, tsFromFile);\n    console.log(`Types generated to ${outputPath}`);\n  } catch (error) {\n    console.error('Error generating types:', error);\n  }\n}\n\ngenerateTypes();\n","lang":"typescript","description":"This quickstart demonstrates how to programmatically compile a JSON Schema to TypeScript types, both from an in-memory object and from a file, using common configuration options. It creates a temporary `schema.json` and outputs `types.d.ts`."},"warnings":[{"fix":"Always explicitly define `additionalProperties` in your JSON Schema (`true`, `false`, or a sub-schema) or pass `{ additionalProperties: false }` (or `true`) in the `Options` object to `compile` or `compileFromFile` to ensure consistent behavior. For CLI, use `--no-additionalProperties` or `--additionalProperties`.","message":"The default behavior for `additionalProperties` was changed in some versions, or its interpretation became stricter. Prior versions might have implicitly allowed additional properties, leading to `[k: string]: any` in generated types. Explicitly setting `additionalProperties` in your schema or via the library's options is highly recommended.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Carefully review schemas using `oneOf`/`anyOf`/`allOf`. Ensure they are unambiguous and provide clear type inference paths. Consider using `discriminator` if applicable for `oneOf` to guide type inference. If `unknown` types appear, simplify the schema or add `tsType` annotations (custom schema properties) as a workaround.","message":"Handling of `oneOf`, `anyOf`, and `allOf` keywords can sometimes lead to `unknown` types or unexpected union types if the schema is ambiguous or complex. This has seen refinements across major versions to improve type precision, but might alter generated types for certain complex schemas.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"For large schemas, set `format: false` in the options object (`{ format: false }`) to disable internal Prettier formatting, then apply formatting manually if needed. For CLI, use `--no-format`.","message":"Performance issues can occur when processing very large or deeply nested JSON Schemas, especially with the default code formatting enabled (which uses Prettier internally).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always refer to the documentation for your specific installed version. For the main `json-schema-to-typescript` package, upgrading to the latest stable version (currently 15.x) is recommended for the most current features and fixes.","message":"Older versions of the library or specific forks might have different default behaviors or removed features, such as `json-schema-to-typescript-lite` removing CLI support and Prettier integration for a lighter footprint.","severity":"deprecated","affected_versions":"<15.0.0"},{"fix":"When using `json-schema-to-typescript` in a browser environment, use the `compile` function with an in-memory JSON Schema object. You will need to fetch the schema content separately if it resides on a server.","message":"The library relies on `fs` for file operations (`compileFromFile`), which is a Node.js-specific module. Direct use of `compileFromFile` in a browser environment will fail.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify that the path to your JSON Schema file is correct and that the file has appropriate read permissions. Ensure relative paths are resolved correctly, e.g., using `path.join(__dirname, 'your-schema.json')`.","cause":"The `compileFromFile` function was called with a file path that does not exist or is inaccessible.","error":"Error: ENOENT: no such file or directory, open 'your-schema.json'"},{"fix":"Ensure your project is configured for ES modules (e.g., `\"type\": \"module\"` in `package.json`) and that you are using `import { compile } from 'json-schema-to-typescript'` syntax. If running directly in Node.js, confirm your file uses `.mjs` extension or `type: module`.","cause":"This error often indicates a CommonJS module trying to import an ESM-only package, or a bundling/transpilation issue where ES module exports are not correctly resolved.","error":"TypeError: (0, json_schema_to_typescript_1.compile) is not a function"},{"fix":"Refactor your imports to use ES module `import` syntax: `import { compile, compileFromFile } from 'json-schema-to-typescript'`. If you need conditional imports, consider dynamic `import()`.","cause":"You are attempting to use `require()` in an ES module (`.mjs` file or `\"type\": \"module\"` project) where CommonJS `require` is not available.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Set `\"additionalProperties\": false` in your JSON Schema to disallow undeclared properties, or pass `{ additionalProperties: false }` to the `compile` options. Alternatively, if `additionalProperties` is desired, ensure all explicitly defined properties are not `undefined` or handle them appropriately.","cause":"This TypeScript error can occur when `additionalProperties` is implicitly or explicitly `true` in your schema, leading to `[k: string]: any` (or similar) but a property within `properties` is `undefined` due to `strictNullChecks`.","error":"TS2411: Property 'x' of type 'string | undefined' is not assignable to string index type 'string'."}],"ecosystem":"npm"}