Type Inference : Named Types with nested schemas in objects
See original GitHub issueHey everyone! I’ve recently discovered Zod and this is quite a marvel! Congrats @colinhacks and every contributor for the awesome work !
I’ve got an “issue” that can be quite annoying when dealing with complex objects, let me explain with this short example :
const foo = z.object({
name: z.string(),
birthdate: z.date()
})
type Foo = z.infer<typeof foo>
const bar = z.object({
property: z.string(),
foo
})
type Bar = z.infer<typeof bar>
Here i defined two schemas, a practical example would be : Foo is a Person, and Bar is an Order or something, it doesn’t matter. When I infer the type of Bar, I would like the final output to look like this :
type Bar = {
property: string;
foo: Foo;
}
Of course right now, this is impossible, I’ve searched the docs and tried a few things, but unfortunately nothing worked.
What the inferred type looks like (no surprise here)
type Bar = {
property: string;
foo: {
name: string;
birthdate: Date;
};
}
What i’ve tried so far, without any luck
const bar = z.object({
property: z.string(),
foo: foo as z.ZodSchema<Foo>
})
const bar = z.object({
property: z.string(),
foo: foo.transform((arg): Foo => { return arg })
})
My terrible workaround
type Bar = { property: string, foo: Foo }
Why I consider it important With large DB infrastructures, having understandable and clear typings is essential, while Zod allows me to really enforce typing, I would really like to have a clear type hinting from VSCode when using z.infer<T>. The workaround is fine but it’s static.
Have anyone figured out how to achieve such behavior ?
Cheers! Julien
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
Top GitHub Comments
So far no solution was provided. While there is one, of course not that shiny.
TypeScript Playground link
another way to tackle this could be to create IDE extensions