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

Omitting a literal from a union of literals results in an array-like object #506

Open RohanTalip opened 2 years ago

RohanTalip commented 2 years ago

Starting from https://github.com/YousefED/typescript-json-schema/blob/1b65adb0cd56cbad61200533ebe5982e85d87c5b/test/programs/string-literals/main.ts , I created a version that uses Omit:

type result = "ok" | "fail" | "abort" | "";
type not_ok = Omit<result, "ok">;

class MyObject {
    foo: not_ok;
    bar: result | string;
}

With typescript-json-schema version 0.54.0 (and in fact from version 0.38.0 onwards1), this code generates this JSON schema:

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

1: Some earlier versions required type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; to also be defined (it was added in later versions of TypeScript).

With typescript-json-schema version 0.37.0, a test file of:

type result = "ok" | "fail" | "abort" | "";

type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type not_ok = Omit<result, "ok">;

class MyObject {
    foo: not_ok;
    bar: result | string;
}

... generates this JSON schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "properties": {
        "bar": {
            "type": "string"
        },
        "foo": {
            "items": {
                "type": "string"
            },
            "type": "array"
        }
    },
    "required": [
        "bar",
        "foo"
    ],
    "type": "object"
}

Is the original array type expected in version 0.37.0? Is the new array-like object expected from version 0.38.0 onwards?

It looks like https://github.com/YousefED/typescript-json-schema/pull/277 changed this behaviour, and indeed when I checked out version 0.38.0 and removed the ts.ObjectFlags.Mapped that was added in typescript-json-schema.ts, the original array type is generated for my test file above.