YousefED / typescript-json-schema

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

Intersection with `{}` breaks schema #489

Open alan-nf opened 2 years ago

alan-nf commented 2 years ago

Using v0.53.1:

export interface Toggleable {
  enabled: boolean;
}

export type ScrewsUpSchemaConfig = Toggleable & {};

export type DoesNotGetEnabledPropConfig = Toggleable & {
  response: string;
};

export interface Config {
  screwsUpSchema?: ScrewsUpSchemaConfig;
  doesNotGetEnabled?: DoesNotGetEnabledPropConfig;
}

typescript-json-schema --noExtraProps --strictNullChecks --required ./tsconfig.json Config > schema.json produces:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "additionalProperties": false,
    "definitions": {
        "Toggleable": {
            "additionalProperties": false,
            "properties": {
                "enabled": {
                    "type": "boolean"
                }
            },
            "required": [
                "enabled"
            ],
            "type": "object"
        }
    },
    "properties": {
        "doesNotGetEnabled": {
            "additionalProperties": false,
            "properties": {
                "response": {
                    "type": "string"
                }
            },
            "required": [
                "response"
            ],
            "type": "object"
        },
        "screwsUpSchema": {
            "$ref": "#/definitions/Toggleable"
        }
    },
    "type": "object"
}

Note that if I give ScrewsUpSchemaConfig any properties (instead of {}):

export type ScrewsUpSchemaConfig = Toggleable & { a: number };

Then doesNotGetEnabled DOES get the enabled property:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "additionalProperties": false,
    "properties": {
        "doesNotGetEnabled": {
            "additionalProperties": false,
            "properties": {
                "enabled": {
                    "type": "boolean"
                },
                "response": {
                    "type": "string"
                }
            },
            "required": [
                "enabled",
                "response"
            ],
            "type": "object"
        },
        "screwsUpSchema": {
            "additionalProperties": false,
            "properties": {
                "a": {
                    "type": "number"
                },
                "enabled": {
                    "type": "boolean"
                }
            },
            "required": [
                "a",
                "enabled"
            ],
            "type": "object"
        }
    },
    "type": "object"
}

Note: another workaround is to convert doesNotGetEnabled to use an interface that extends Toggleable

Similar to https://github.com/YousefED/typescript-json-schema/issues/359 (in that they both deal with intersection types)