Open enchorb opened 6 months ago
This depends on what type util you're using to infer the type? Are you using infer, input or output?
I use infer
for my types and that works fine, types are as expected. This fails after safeParse
/ parse
where the output for all preprocessed types is unknown
const product_validation = z.object({
name: string_validation
description: z.string(),
hidden: boolean_validation.default(false),
popular: z.boolean()
}).partial();
// Types Are As Expected
export type Product = z.infer<typeof product_validation>;
// Types Are Unknown For All Preprocessed Types
const parsed = product_validation.safeParse({ name: 'Test Product', description: 'This is a product', hidden: false, popular: true )}.data;
Looks fine to me in this playground
I think I have a similar issue. For me it appears when using z.ZodType
.
See this playground.
import {z} from 'zod';
const preprocessSchema = z.preprocess((val) => (val === '' ? null : val), z.coerce.date());
const noPreprocessSchema = z.coerce.date();
function doSafeParse<T>(schema: z.ZodType<T>) {
return schema.safeParse({})
}
// unknown -- broken?
const parsed = doSafeParse(preprocessSchema).data;
// Date | undefined
const parsed2 = preprocessSchema.safeParse({}).data;
// Date | undefined
const parsed3 = doSafeParse(noPreprocessSchema).data;
// Date | undefined
const parsed4 = noPreprocessSchema.safeParse({}).data;
I think I have a similar issue. For me it appears when using
z.ZodType
.See this playground.
import {z} from 'zod'; const preprocessSchema = z.preprocess((val) => (val === '' ? null : val), z.coerce.date()); const noPreprocessSchema = z.coerce.date(); function doSafeParse<T>(schema: z.ZodType<T>) { return schema.safeParse({}) } // unknown -- broken? const parsed = doSafeParse(preprocessSchema).data; // Date | undefined const parsed2 = preprocessSchema.safeParse({}).data; // Date | undefined const parsed3 = doSafeParse(noPreprocessSchema).data; // Date | undefined const parsed4 = noPreprocessSchema.safeParse({}).data;
You aren't declaring your function types correctly. Please read this.
The type returned from z.preprocess is giving out type
unknown
It's annoying but don't use preprocess in too many places so for now fixing by setting the type explicitly