Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

ZodType is not contravariant to the input #3795

Open
mstniy opened this issue Oct 12, 2024 · 0 comments · May be fixed by #3796
Open

ZodType is not contravariant to the input #3795

mstniy opened this issue Oct 12, 2024 · 0 comments · May be fixed by #3796

Comments

@mstniy
Copy link

mstniy commented Oct 12, 2024

Background

Contravariance is a property associated of generic types on their type parameters where the generic type G<A> extends G<B> if B extends A. It is usually associated with type parameters used as inputs.

Each ZodType is composed of an input and an output type. Consider, for instance, the following Zod schema:

const s = z.object({
    a: z.string().default("foo")
});

Its input type has a as an optional field, but it is required on the output type:

type A = z.input<typeof s>; // { a?: string | undefined; }
type B = z.output<typeof s>; // {a: string}

Description

Given that the input and output types are type parameters to ZodType, one might expect ZodType to be covariant on the output type and contravariant on the input type. While the former is true, the latter, unfortunately, is not.

Example

function f<S extends z.ZodType<string, any, any>>(_: S) {}
f(z.literal("a")); // Works fine

function g<S extends z.ZodType<any, any, "a">>(_: S) {}
g(z.string()); // Errors out :(

Expected behaviour

ZodType should be contravariant with respect to the input type

Actual behaviour

ZodType is not contravariant with respect to the input type

@mstniy mstniy linked a pull request Oct 12, 2024 that will close this issue
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant