json-schema-to-typescript

repository·master·Indexed 25 days ago

https://github.com/bcherny/json-schema-to-typescript

A 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.

Tokens
3.5K
Snippets
3
Records
19
Agent score
79%

What's inside json-schema-to-typescript

  1. Use the json2ts CLI

    master

    The json2ts command-line interface allows you to compile JSON schemas into TypeScript declaration files (.d.ts).

    Input and Output Behavior

    • Standard Input: If no IN_FILE is provided, or if -i - is used, the CLI reads from stdin.
    • Single File Output: If an IN_FILE is specified but no OUT_FILE is provided, the .d.ts file is created in the same directory as the input file.
    • Standard Output: If neither IN_FILE nor OUT_FILE is provided, the resulting TypeScript code is written to stdout.
    • Multi-file Input: You can provide a glob pattern or a directory as the input. If an OUT_FILE is provided for a multi-file input, it is treated as a directory where individual .d.ts files will be generated.

    Usage Syntax

    json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE] [OPTIONS]
  2. Extend JSON Schema with `tsEnumNames` and `tsType`

    master

    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.
  3. Configure json-schema-to-typescript via Options

    master

    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.
  4. Use custom JSON-schema properties for type overrides

    master

    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.
  5. Reference: compile and compileFromFile options

    master

    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 |
  6. Use the json2ts CLI

    master

    You can use the json2ts command-line interface to convert JSON or YAML files to TypeScript typings.

    To make the CLI available, you can:

    1. Install locally: npm install json-schema-to-typescript and use npx json2ts.
    2. Install globally: npm install json-schema-to-typescript --global and use json2ts.
    3. Use via npm cache without installing: npx --package=json-schema-to-typescript json2ts.
  7. Compile JSON Schema to TypeScript using compile()

    master

    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.