z.ZodType and z.ZodSchema do not seem to work as I expect
See original GitHub issueHi there!
I’ve discovered the lib recently and have a question that is probably silly.
I have an application that defines its domain with Typescript, which I want to be the single source of truth. This means I’m not interested in inferring static types from Zod, but the other way around. I want Zod to obey what Typescript dictates and want the TS compiler to let me know when any inconsistency arises. I assume the dual definition of types and parsers.
I’ve tried to achieve this with z.ZodType<MyType>
and z.ZodSchema<MyType>
with no success and I have not found a clue to follow from the readme of the project, which seems to be the only documentation available.
I’ve prepared a small dumb example that I hope will help you understand what I intend to do (CodeSandbox here):
import * as z from "zod";
type A = {
foo: string;
bar: string;
};
// This parser exactly matches interface A so we have no errors. So far so cool.
const AParser: z.ZodType<A> = z.object({
foo: z.string(),
bar: z.string()
});
///////////////////////////////////////////////////////////////
type B = {
bar: string;
};
// Why I get no errors on a parser that does not match the type z.ZodType<B>?
const BParser: z.ZodType<B> = z.object({
foo: z.string(),
bar: z.string()
});
I have some experience with io-ts
. Please find here a CodeSandbox demonstrating the result I’d expect.
Thx!!
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5
Top GitHub Comments
Just for reference and in case it’s useful for someone else facing these problems, we’ve ended up applying this solution, which works quite well for us since the compiler warns us whenever there’s an inconsistency between the TS types and the Zod parsers.
Exact
returnstrue
whenever the 2 generic types match andfalse
otherwise.StrictSchema
accepts a generic type and returns a function that expects aZodSchema
as param.I’ve updated the CodeSandbox to demonstrate how it works (from line 38) and it seems to work in all the cases:
Credits should go to @yuhr, who put us on the right track.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.