ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.4k stars 30 forks source link

TypeScript error when using `nullable` in a definition schema #191

Closed adriencaccia closed 4 months ago

adriencaccia commented 4 months ago

Hey, there is a TypeScript error when using nullable in a definition schema.

import type { FromSchema, JSONSchema } from "json-schema-to-ts";

const FooSchema = {
  type: "object",
  properties: {
    bar: { $ref: "#/$defs/Bar" },
  },
  required: ["bar"],
  $defs: {
    Bar: {
      type: "object",
      properties: {
        baz: {
          type: "string",
          nullable: true,
        },
      },
    }
  },
} as const satisfies JSONSchema;

type Foo = FromSchema<typeof FooSchema>;

The type Foo is correct with:

type Foo = {
    [x: string]: unknown;
    bar: {
        [x: string]: unknown;
        baz?: string | null | undefined;
    };
}

But there is a TypeScript error at the nullable: true line:

Object literal may only specify known properties, and 'nullable' does not exist in type 'JSONSchema7'.ts(2353)

It would be great to not have this error, as this works at the type level.

Thanks!

ThomasAribart commented 4 months ago

Hi @adriencaccia and thanks for the issue !

It should work fine with v3.0.1, although you'll have to rename $defs to definitions:

const FooSchema = {
  type: "object",
  properties: {
    bar: { $ref: "#/definitions/Bar" },
  },
  required: ["bar"],
  definitions: {
    Bar: {
      type: "object",
      properties: {
        baz: {
          type: "string",
          nullable: true,
        },
      },
    }
  },
} as const satisfies JSONSchema;

type Foo = FromSchema<typeof FooSchema>; // should work fine!
adriencaccia commented 4 months ago

Thank you for the quick fix, it works perfectly 👍