ThomasAribart / json-schema-to-ts

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

Definitons in references not resolved #172

Open toteto opened 9 months ago

toteto commented 9 months ago

When there is referenced schema that contains properties that contains property defined in the definitions, the property type is being resolved to undefined.

Example:

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

const FooSchema = {
    $schema: 'http://json-schema.org/draft-07/schema',
    type: 'object',
    properties: {
        bar: {
            $ref: 'https://example.com/bar.json',
        },
    },
} as const satisfies JSONSchema;

const BarSchema = {
    $schema: 'http://json-schema.org/draft-07/schema',
    $id: 'https://example.com/bar.json',
    type: 'object',
    definitions: {
        name: {
            type: 'string',
        },
    },
    properties: {
        name: {
            $ref: '#/definitions/name',
        },
        age: {
            type: 'number',
        },
    },
} as const satisfies JSONSchema;

type FooType = FromSchema<typeof FooSchema, { references: [typeof BarSchema] }>;
// Result: type FooType = {
//   [x: string]: unknown;
//   bar?: {
//       [x: string]: unknown;
//       name?: undefined;
//       age?: number | undefined;
//   } | undefined;
// }

const foo: FooType = {
    bar: {
        name: 'Antonio', // Error: Type 'string' is not assignable to type 'undefined'
        age: 42,
    },
};

In the README there is the line under the Definitions section that states ☝️ Wether in definitions or references,FromSchemawill not work on recursive schemas for now. (link)

If this is not supposed to be supported, is there another workaround that we can get the type even in some more manual way?