2.1.1 • Published 1 year ago

json-schema-typescript-generator v2.1.1

Weekly downloads
117
License
MIT
Repository
github
Last release
1 year ago

json-schema-typescript-generator

Generate typescript files from json schema files

Contents

Install

Usage

Typescript

JSONSchema

Approach

Install

Install via one of the commands

npm -i json-schema-typescript-generator -D
yarn add json-schema-typescript-generator -D

Usage

To generate .ts files, invoke the generateFiles function with an Options object like so

import { generateFiles, Options } from 'json-schema-typescript-generator';

const options: Options = {...}
await generateFiles(options);

The Options object is defined as follows:

{
  files: {
    cwd: string;
    source: {
      dir: string;
      encoding: BufferEncoding;
      recursive: boolean;
    }
    destination: {
      dir: string;
      preClean: boolean;
      indexFiles: boolean;
    }
  }
  ts: {
    optionalFields: OptionalFieldPattern;
    untyped: UntypedType;
  }
}

All options are optional and fall back to their defaults if not given, which are as follows:

{
  files: {
    cwd: process.cwd(),
    source: {
      dir: 'src/schemas',
      encoding: 'utf-8',
      recursive: true
    },
    destination: {
      dir: 'src/generated',
      preClean: false,
      indexFiles: true
    }
  },
  ts: {
    optionalFields: OptionalFieldPattern.QUESTION,
    untyped: UntypedType.UNKNOWN
  }
}

The option

options.files.destination.preClean;

defines whether the destination folder will be deleted before generating typescript files.

The option

options.files.destination.indexFiles;

defines whether index.ts files will be generated in each destination folder.

Note that the folders given by the options

options.files.source.dir;
options.files.destination.dir;

will be resolved relative to the folder given by the option

options.files.cwd;

Typescript

There are 2 options which define the style of code generated

OptionalFieldPattern

The option

options.ts.optionalFields;

defines how optional fields are represented and can take 1 of 2 values:

OptionalFieldPattern.QUESTION;

type Example = {
  a?: string;
};

or

OptionalFieldPattern.PIPE_UNDEFINED;

type Example = {
  a: string | undefined;
};

UntypedType

The option

options.ts.untyped;

defines the fallback type used for types that failed to be generated, eg. perhaps the schema was empty, or an id was missing or a typo was made in a $ref entry etc. It can take 1 of 4 values:

UntypedType.ANY;

type Example = {
  a: any;
};

or

UntypedType.NEVER;

type Example = {
  a: never;
};

or

UntypedType.UNDEFINED;

type Example = {
  a: undefined;
};

or

UntypedType.UNKNOWN;

type Example = {
  a: unknown;
};

JSONSchema

Support for properties defined in the JSON Schema are as follows:

KeySupportNotes
$id
$schemaAction in TODO to support specific schema versions
$reflocal definitionabsolute reference to root/inner definitionrelative reference to root/inner definition
$defsCombined with definitions
constnullbooleansnumbersstrings
enumnullbooleansnumbersstrings
type"null""boolean""integer""number""string""array""object"Or an array of the above
number propertiesmultipleOfminimummaximumexclusiveMinimumexclusiveMaximumNo typescript support for multipleOfOpen question on GitHub about number ranges
string propertiesminLengthmaxLengthpatternformatTypescript support for string patterns and formats in v4.1Typescript's implementation produces a union of every possible combination so is not suitable for patterns or formats
array propertiesitemsuniqueItemsadditionalItemsT[] - Array if items is a schema and uniqueItems=falseMap<K, V> - Map if items is a schema, uniqueItems=true, additionalItems=false and items has no other propertiesSet<T> - Set if items is a schema, uniqueItems=true and is not a Map[T, U, V] - Tuple if items is an array
array propertiescontainsminItemsmaxItemsarray (and possibly tuple) min length: type MinLengthArray<T> = [T, T, ...T[]]; Although no typescript support for a Set<T> of specific sizeNo typescript support for contains
object propertiespropertiesadditionalProperties
combinationsallOfanyOfoneOfIf oneOf is used, OneOf_n types are dynamically generated in files that need them, for arrays with many items these types can get large and will be updated if typescript adds native support

Approach

The approach this package takes is to only do one thing but do it well, ie. transforming schema files to typescript files. It doesn't download any schemas, or do any validation, consistency checking, linting, prettifying etc. It assumes the schema author knows exactly what they want and it will generate typescript files that represent the schemas given as closely as possible, even if the generated types don't make sense or cannot be satisfied.

An example will make this clear:

Given the following schema in a file called A.json

{
  "type": "number",
  "$ref": "#/definitions/BOOL",
  "enum": [
    null,
    "tuv",
    "xyz"
  ],
  "definitions": {
    "BOOL": {
      "type": "boolean"
    }
  }
}

Invoking the generator will generate a file A.ts containing:

export type A = BOOL & (null | "tuv" | "xyz") & number;

export type BOOL = boolean;

Clearly type A cannot ever be satisfied, but it does match what the schema specified

2.1.1

1 year ago

1.5.14

1 year ago

2.1.0

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.5.10

2 years ago

1.5.12

2 years ago

1.5.11

2 years ago

1.5.13

2 years ago

1.5.9

3 years ago

1.5.8

3 years ago

1.5.7

3 years ago

1.5.5

3 years ago

1.5.4

3 years ago

1.5.6

3 years ago

1.5.3

3 years ago

1.5.2

3 years ago

1.5.1

3 years ago

1.5.0

3 years ago

1.4.0

3 years ago

1.3.4

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.2.1

3 years ago

1.1.1

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.0

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago