ts-to-zod icon indicating copy to clipboard operation
ts-to-zod copied to clipboard

lookup key in union type results in invalid zod-code

Open bigmistqke opened this issue 1 year ago • 2 comments

Bug description

lookup of keys in union-types result in invalid zod-code.

Input

type Union= [{id: "string"}, {id: 0}]
type Id = Union["id"]

Output

import { z } from "zod"

const unionSchema = z.tuple([
  z.object({
    id: z.literal("string")
  }),
  z.object({
    id: z.literal(0)
  })
])

const idSchema = unionSchema.shape.id

but shape is not an existing property of unionSchema.

In my own codebase I solved the issue with the following code so you can do the following:

const idSchema = z.union(lookup(unionSchema, "id")) // z.union([z.literal("string"), z.literal(0)])

This only works with unions of objects. AFAIK lookup in union of object-types are currently not supported in zod.

Versions

  • Typescript: v5.0.4
  • Zod: v3.21.4

bigmistqke avatar Jun 12 '23 17:06 bigmistqke

Good catch, the .shape is only there for z.object

image

fabien0102 avatar Jun 27 '23 11:06 fabien0102

Hello,

Shouldn't the input be:

type Union = [{ id: "string" }, { id: 0 }];
type Id = Union[number]["id"];
``` 

That doesn't change the fact that the generated output is relying on `shape` which doesn't exist on `ZodTuple`

tvillaren avatar Aug 26 '24 21:08 tvillaren