Install json-schema-to-typescript
masterInstall the package via npm to use it in your project.
npm install json-schema-to-typescriptrepository·master·Indexed 25 days ago
https://github.com/bcherny/json-schema-to-typescriptA tool to compile JSON Schema definitions into TypeScript typings. It provides a CLI (`json2ts`) for build pipelines and a programmatic API featuring `compile` and `compileFromFile` functions. The library supports custom type overrides via `tsType` and `tsEnumNames`, Prettier formatting, and configurable options for resolving $ref, handling enums, and managing index signatures.
Install the package via npm to use it in your project.
npm install json-schema-to-typescriptTo run the demonstration project, install dependencies and build the project. This process compiles the example index.ts to JavaScript and generates a person.d.ts file from the person.json schema file.
# Using Yarn:
yarn
yarn build
# Or, using NPM:
npm install
npm run buildcompile and compileFromFile accept an optional configuration object as the last argument. Use these keys to control the generation process.The json2ts command-line interface allows you to compile JSON schemas into TypeScript declaration files (.d.ts).
IN_FILE is provided, or if -i - is used, the CLI reads from stdin.IN_FILE is specified but no OUT_FILE is provided, the .d.ts file is created in the same directory as the input file.IN_FILE nor OUT_FILE is provided, the resulting TypeScript code is written to stdout.OUT_FILE is provided for a multi-file input, it is treated as a directory where individual .d.ts files will be generated.json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE] [OPTIONS]format option to false in your configuration.compile or compileFromFile to use the library programmatically in your TypeScript or JavaScript code.When providing a JSON Schema to the library, you can use specific schema extensions to influence the generated TypeScript output:
tsEnumNames: An array of strings used to support numeric enums (provides human-readable names for numeric values).tsType: A string used to support custom types.deprecated: A boolean flag to mark properties as deprecated.The Options interface allows you to customize the TypeScript generation process. You can pass a Partial<Options> to the compile or compileFromFile functions.
Commonly used options include:
cwd: The root directory for resolving $refs.format: Whether to format the output code (uses Prettier). Set to false for better performance.style: A Prettier configuration object to control code styling.unknownAny: If true, generates unknown instead of any for unknown types.strictIndexSignatures: If true, appends | undefined to index signatures for compatibility with strictNullChecks.additionalProperties: Default value for additionalProperties when not explicitly set.bannerComment: A disclaimer comment prepended to the top of each generated file.$refOptions: Options passed to @apidevtools/json-schema-ref-parser for resolving $refs.You can use non-standard JSON schema extensions to control how specific parts of your schema are converted to TypeScript:
tsType: Overrides the generated type. Useful for forcing a type to any or using non-standard extensions.tsEnumNames: Overrides the names used for enum elements. Can also be used to create string enums.The following options are available for the compile and compileFromFile functions.
| key | type | default | description |
|---|---|---|---|
| additionalProperties | boolean | `true` | Default value for `additionalProperties`, when it is not explicitly set |
| bannerComment | string | `"/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSON Schema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/"` | Disclaimer comment prepended to the top of each generated file |
| customName | `(LinkedJSONSchema, string \| undefined) => string \| undefined` | `undefined` | Custom function to provide a type name for a given schema |
| cwd | string | `process.cwd()` | Root directory for resolving [`$ref`](https://tools.ietf.org/id/draft-pbryan-zyp-json-ref-03.html)s |
| declareExternallyReferenced | boolean | `true` | Declare external schemas referenced via `$ref`? |
| enableConstEnums | boolean | `true` | Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)? |
| inferStringEnumKeysFromValues | boolean | `false` | Create enums from JSON enums with eponymous keys |
| format | boolean | `true` | Format code? Set this to `false` to improve performance. |
| ignoreMinAndMaxItems | boolean | `false` | Ignore maxItems and minItems for `array` types, preventing tuples being generated. |
| maxItems | number | `20` | Maximum number of unioned tuples to emit when representing bounded-size array types, before falling back to emitting unbounded arrays. Increase this to improve precision of emitted types, decrease it to improve performance, or set it to `-1` to ignore `maxItems`. |
| strictIndexSignatures | boolean | `false` | Append all index signatures with `\| undefined` so that they are strictly typed. |
| style | object | `{ bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false }` | A [Prettier](https://prettier.io/docs/options.html) configuration |
| unknownAny | boolean | `true` | Use `unknown` instead of `any` where possible |
| unreachableDefinitions | boolean | `false` | Generates code for `$defs` that aren't referenced by the schema. |
| $refOptions | object | `{}` | [$RefParser](https://github.com/APIDevTools/json-schema-ref-parser) Options, used when resolving `$ref`s |You can use the json2ts command-line interface to convert JSON or YAML files to TypeScript typings.
To make the CLI available, you can:
npm install json-schema-to-typescript and use npx json2ts.npm install json-schema-to-typescript --global and use json2ts.npx --package=json-schema-to-typescript json2ts.Use the compile function to transform a JSON Schema object into TypeScript code. It accepts the schema object, a name for the generated types, and an optional configuration object. It returns a Promise<string> containing the generated TypeScript code.
Note: This function may throw a ValidationError if the schema is invalid.