ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas đź“ť
MIT License
1.43k stars 30 forks source link

Array element type should be possibly 'undefined' #117

Closed amiran-gorgazjan closed 1 year ago

amiran-gorgazjan commented 1 year ago

Expected behavior

Given a schema:

{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "id": {
                "type": "number"
            }
        }
    }
}

It will pass validation against:

[{id: 1}] // Passes!
[] // Passes!

See also: https://www.jsonschemavalidator.net/s/Plkz5SSq

Therefore, the type of the above array should be ({ id: number } | undefined)[]

And we would expect the following to show a TS error:

myArray[0].id // Should show: Object possibly 'undefined'

Actual behavior

json-schema-to-ts currently results in the type { id: number }[] and therefore the above reference error is not caught and will fail at runtime.

The same issue is already present in the README.md first example:

const dogSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer" },
    hobbies: { type: "array", items: { type: "string" } },
    favoriteFood: { enum: ["pizza", "taco", "fries"] },
  },
  required: ["name", "age"],
};

type Dog = {
  name: string;
  age: number;
  hobbies?: string[];
  favoriteFood?: "pizza" | "taco" | "fries";
};

hobbies?: string[]; should actually be hobbies?: (string | undefined)[];

amiran-gorgazjan commented 1 year ago

Nevermind, this bug report is incorrect - it turns out actually TypeScript behaves like this and the generated type by this library itself is correct. Closing.

ThomasAribart commented 1 year ago

Hello @amiran-gorgazjan ! Yes I don't think it's an issue with FromSchema.

You can use the noUncheckedIndexedAccess ts option: https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess