YousefED / typescript-json-schema

Generate json-schema from your Typescript sources
BSD 3-Clause "New" or "Revised" License
3.14k stars 322 forks source link

Changing whether a field is optional (`?`) changes the schema #583

Open samuelcolvin opened 9 months ago

samuelcolvin commented 9 months ago

Great library, thanks so much.

When I have a required field which has type of a union which is itself defined as a type, the field is just a ref to that type, when I make the field optional with ?, I get an anyOf, not a $ref.

If this is intentional and therefore won't be changed, is there a way to change behaviour to be consistent?

Example - field required

type FooBar = number | string

export interface Demo {
  thing: FooBar
}

Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "FooBar": {
      "type": ["string", "number"]
    }
  },
  "properties": {
    "thing": {
      "$ref": "#/definitions/FooBar"
    }
  },
  "required": ["thing"],
  "type": "object"
}

Example - field not required

type FooBar = number | string

export interface Demo {
  thing?: FooBar
}

Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "properties": {
    "thing": {
      "type": ["string", "number"]
    }
  },
  "type": "object"
}
domoritz commented 9 months ago

Have you tried https://github.com/vega/ts-json-schema-generator? It's the generator I actively maintain.