Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

converting a recursive json schema into a zod type breaks #2508

Open
jonnytest1 opened this issue Feb 16, 2024 · 1 comment
Open

converting a recursive json schema into a zod type breaks #2508

jonnytest1 opened this issue Feb 16, 2024 · 1 comment
Labels
bug good first issue Not necessarily easy, but doesn't require deep quicktype knowledge input:JSON Schema JSON Schema Input TS Zod TypeScript Zod Output

Comments

@jonnytest1
Copy link

jonnytest1 commented Feb 16, 2024

example self referential schema:

{
  "id": "http://json-schema.org/geo",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "description": "A geographical coordinate",
  "type": "object",
  "definitions":{
    "Mydef1":{
        "type":"object",
        "properties":{
            "test":{
                "$ref":"#/definitions/Mydef1"
            }
            
        }
    }
  },
  "properties": {
    "latitude": {
       "$ref":"#/definitions/Mydef1"
    }
  }
}

produces:

export const Mydef1Schema = z.object({
    "test": z.union([Mydef1Schema, z.null()]).optional(),
});
export type Mydef1 = z.infer<typeof Mydef1Schema>;

export const CoordinateSchema = z.object({
    "latitude": z.union([Mydef1Schema, z.null()]).optional(),
});
export type Coordinate = z.infer<typeof CoordinateSchema>;

but it should be
https://github.com/colinhacks/zod#recursive-types

=> z.lazy(() => Mydef1Schema)

export const Mydef1Schema = z.object({
    "test": z.union([z.lazy(() =>Mydef1Schema), z.null()]).optional(),
});
export type Mydef1 = z.infer<typeof Mydef1Schema>;

export const CoordinateSchema = z.object({
    "latitude": z.union([Mydef1Schema, z.null()]).optional(),
});
export type Coordinate = z.infer<typeof CoordinateSchema>;
@jonnytest1
Copy link
Author

jonnytest1 commented Feb 16, 2024

a relatively easy approach would probably be to wrap ALL schemas into z.lazy 🤔 which should work fine at least for the runtime evaluation

@inferrinizzard inferrinizzard added TS Zod TypeScript Zod Output good first issue Not necessarily easy, but doesn't require deep quicktype knowledge bug input:JSON Schema JSON Schema Input labels May 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug good first issue Not necessarily easy, but doesn't require deep quicktype knowledge input:JSON Schema JSON Schema Input TS Zod TypeScript Zod Output
Projects
None yet
Development

No branches or pull requests

2 participants