bcherny/json-schema-to-typescript

Support for boolean JSON Schemas

Open

#496 创建于 2022年11月22日

在 GitHub 查看
 (6 评论) (3 反应) (0 负责人)TypeScript (449 fork)github user discovery
enhancementgood first issuehelp wanted

仓库指标

Star
 (3,302 star)
PR 合并指标
 (30 天内没有已合并 PR)

描述

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
}

贡献者指南