fabien0102 / ts-to-zod

Generate zod schemas from typescript types/interfaces
MIT License
1.22k stars 67 forks source link

[Bug] Validation fails when using `undefined` primitive in non-optional property #239

Closed tvillaren closed 5 months ago

tvillaren commented 5 months ago

Input

export type User = {
  username: string | undefined
}

Expected output

// Generated by ts-to-zod
import { z } from "zod";

export const userSchema = z.object({
  username: z.union([z.string(), z.undefined()]),
});

Actual output

✖ Validating generated types
Error: 'userSchema' is not compatible with 'User':
Argument of type '{ username?: string | undefined; }' is not assignable to parameter of type 'User'.
  Property 'username' is optional in type '{ username?: string | undefined; }' but required in type 'User'.

Originally posted by @johnnyp-gg in https://github.com/fabien0102/ts-to-zod/issues/203#issuecomment-2104798136

tvillaren commented 5 months ago

The validation error you're getting comes from a known bug in Zod inference (https://github.com/colinhacks/zod/issues/2464) To be checked if we can ignore it (as for #140)

johnnyp-gg commented 5 months ago

Thanks @tvillaren, its working fine for me now!