ts-to-zod
ts-to-zod copied to clipboard
lookup key in union type results in invalid zod-code
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
Good catch, the .shape
is only there for z.object
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`