StefanTerdell / json-schema-to-zod

ISC License
338 stars 48 forks source link

Suggestion for intersection types #109

Open rsan-one-network opened 3 months ago

rsan-one-network commented 3 months ago

Right now when the json schema has intersection types you are using the ".and" command to join them together. Would it not be better to use the .merge command as it's suggested in the documentation?

image

In my implementation i need to access the shape attribute of the generated zod objects but ZodIntersection does not have it.

rsan-one-network commented 3 months ago

Json schema example:

{
  "type" : "object",
  "properties" : {
    "attribute1" : {
      "type" : "boolean"
    },
    "attribute2" : {
      "type" : "integer"
    },
    "attribute3" : {
      "type" : "integer"
    }
  },
  "additionalProperties" : false,
  "allOf" : [ {
    "type" : "object",
    "properties" : {
      "attribute4" : {
        "type" : "string"
      },
      "attribute5" : {
        "type" : "integer"
      }
    },
    "additionalProperties" : false
  } ]
}

Current output:

export default z
  .object({
    attribute1: z.boolean().optional(),
    attribute2: z.number().int().optional(),
    attribute3: z.number().int().optional(),
  })
  .strict()
  .and(
    z
      .object({
        attribute4: z.string().optional(),
        attribute5: z.number().int().optional(),
      })
      .strict()
  );

Proposed output:


export default z
  .object({
    attribute1: z.boolean().optional(),
    attribute2: z.number().int().optional(),
    attribute3: z.number().int().optional(),
  })
  .strict()
  .merge(
    z
      .object({
        attribute4: z.string().optional(),
        attribute5: z.number().int().optional(),
      })
      .strict()
  );

`
``
StefanTerdell commented 2 months ago

Sure, let's try it out. Open to PRs