bcherny/json-schema-to-typescript

Support for boolean JSON Schemas

Open

#496 aperta il 22 nov 2022

Vedi su GitHub
 (6 commenti) (3 reazioni) (0 assegnatari)TypeScript (449 fork)github user discovery
enhancementgood first issuehelp wanted

Metriche repository

Star
 (3302 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

Context:

Boolean JSON schemas are true and false:

  • true passes the validation of any input.
  • false fails the validation of any input.

Consider the specs as references:

How do we apply this in the library:

I would suggest the following changes:

  • Whenever a true JSON Schema is transpiled to a type, the transpiled type should be any or unknown (depending on the config).
  • Whenever a false JSON Schema is transpiled to a type, the transpiled type should be never

Examples:

{
     "$schema": "http://json-schema.org/draft/2020-12/schema",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "color": true,
        "kind": true,
        "number": false
      },
      "required": ["color, kind", "number"]
}

should be transpiled to something like:

export interface Foo {
  color: unknown;
  kind: unknown;
  number: never;
}

I know, number: never feels ugly, but never is probably the type which works nicely not only in this simple example but also in more complex ones.

Current behavior:

Boolean JSON schemas are transpiled into their boolean types:

{
  "$schema": "http://json-schema.org/draft/2020-12/schema",
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "foo": true
  },
  "required": ["foo"]
}

is transpiled into:

export interface ExampleSchema {
  foo: true
  [k: string]: unknown
}

instead of

export interface ExampleSchema {
  foo: unknown
  [k: string]: unknown
}

Guida contributor