ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.44k stars 31 forks source link

Recursive ref issue #96

Open djvs opened 1 year ago

djvs commented 1 year ago

Taking this file as an example:

import { O } from "ts-toolbelt"
import { FromSchema } from "json-schema-to-ts"

export const leafTypeSchema = {
  type: "string",
  enum: ["string", "number", "boolean"],
} as const
export type LeafType = FromSchema<typeof leafTypeSchema>

export const objTypeSchema = {
  type: "string",
  const: "object",
} as const
export type ObjType = FromSchema<typeof objTypeSchema>

export const leafSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    id: { type: "string", format: "uuid" },
    key: { type: "string" },
    type: leafTypeSchema,
    name: { type: "string" },
  },
  required: ["id", "key", "type", "name"],
} as const
export type Leaf = FromSchema<typeof leafSchema>

export const objSchema = {
  $id: "objSchema",
  type: "object",
  additionalProperties: false,
  properties: {
    id: { type: "string", format: "uuid" },
    key: { type: "string" },
    type: objTypeSchema,
    name: { type: "string" },
    fields: { type: "array", items: { anyOf: [{ $ref: "#" }, leafSchema] } },
  },
  required: ["id", "key", "type", "name", "fields"],
} as const
export type ObjRaw = FromSchema<typeof objSchema>

export const fieldTypeSchema = {
  anyOf: [leafTypeSchema, objTypeSchema],
} as const
export type FieldType = FromSchema<typeof fieldTypeSchema>

export const fieldSchema = {
  anyOf: [objSchema, leafSchema],
} as const
export type Field = Obj | Leaf

export type Obj = O.Update<ObjRaw, "fields", Array<Field>>

I'm seeing this: Type of property 'fields' circularly references itself in mapped type '{ id: { type: "primitive"; value: string; isSerialized: false; deserialized: never; }; key: { type: "primitive"; value: string; isSerialized: false; deserialized: never; }; type: { type: "const"; value: "object"; isSerialized: false; deserialized: never; }; name: { ...; }; fields: _$Array<...>; }'. (tsserver 2615)

This was working prior to an update from 1.6 to latest (2.5.5). Recommendation on how to resolve?

ThomasAribart commented 1 year ago

Hi @djvs and thanks for the issue !

Yes, for the moment, FromSchema doesn't handle recursive schemas. There's no simple way to fix your issue sadly.

I'm honestly not sure this is achievable, but I'll look into it. Possible solutions are: