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

Wrong schema generation for intersection types #480

Closed DavideCanton closed 9 months ago

DavideCanton commented 2 years ago

Schema generation for intersection types is incorrect.

Starting from the following typescript:

export type T = {
    foo: number;
} & {
    [key: string]: string;
};

if I run the following command: typescript-json-schema ./tsconfig.json T -o schema.json

I get the following schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "allOf": [
        {
            "properties": {
                "foo": {
                    "type": "number"
                }
            },
            "type": "object"
        },
        {
            "additionalProperties": {
                "type": "string"
            },
            "type": "object"
        }
    ]
}

which is not correct, since the following json does not match:

{
    "foo": 0,
    "bar": "a"
}

I get a validation error on the 0: Incorrect type. Expected "string".

I believe the correct schema should be something like this:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "properties": {
        "foo": {
            "type": "number"
        }
    },
    "type": "object",
    "additionalProperties": {
        "type": "string"
    }
}
netanel-mce commented 1 year ago

No data can be valid for this type: image So we not want to support it.

netanel-mce commented 1 year ago

the real issue is this type:

type T = {
    [key: number]: string;
    foo: number;
};

data for example: image

But I got for this type following schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "additionalProperties": false,
    "patternProperties": {
        "^[0-9]+$": {
            "type": "number"
        }
    },
    "type": "object"
}

I expected to got:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "additionalProperties": false,
    "patternProperties": {
        "^[0-9]+$": {
            "type": "number"
        }
    },
    "properties": {
        "foo": {
            "type": "number"
        }
    },
    "type": "object"
}