inferrence for transformed sub schema fails when going through generics #950
-
Let me preface this with that this might just be me having made some bad generics. But it seemed to work before I changed all my string based ISO-8601 dates to be Full repro repo here: https://github.com/karl-run/zod-repro DetailsWhen you have a zod type that transforms a string to a date, for example like this: export const LocalDateSchema = z
.string()
.refine((date) => isValid(parseISO(date)), { message: "Invalid date string" })
.transform((date) => parseISO(date)); The resulting type here would be Given this example type, with it's corresponding (generated from GraphQL schema type): const SchemaWithDate = z.object({
a: z.string(),
date: LocalDateSchema,
c: z.string(),
});
interface CompatibleGraphQLSchemaWithDate {
a: string;
date: Date;
c: string;
} Parsing like this give you the expected result: const workingResult = SchemaWithDate.safeParse({});
if (workingResult.success) {
const reAssign: CompatibleGraphQLSchemaWithDate = workingResult.data
} So far so good. But I had this function that infers the type from the schema, so I could have one fetch function that passes inn path and schema, and parses and infers correctly (simplified for repro): async function genericFetcher<SchemaType>({
path,
schema,
}: {
path: string;
schema: ZodType<SchemaType>;
}): Promise<SchemaType> {
const response = await fakeFetch(path);
const responseJson = await response.json();
const result = schema.safeParse(responseJson);
if (result.success) {
return result.data;
}
throw new Error(`Unable to parse response`);
} Now if we parse using this function, we get some strange behaviour: const doesNotWork: CompatibleGraphQLSchemaWithDate = await genericFetcher({
path: "/foo",
schema: SchemaWithDate,
}); Gives us the following error on
Implying that the transformed Again, full repro here if anyone would like to play around with it: https://github.com/karl-run/zod-repro |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I also tried making the generics more explicit: async function genericFetcher<Result, SchemaType extends ZodType<Result>>({
path,
schema,
}: {
path: string;
schema: SchemaType;
}): Promise<Result> { But it still sees the transformed date as a |
Beta Was this translation helpful? Give feedback.
-
Try this async function genericFetcher<SchemaType extends z.ZodTypeAny> ( {
path,
schema,
}: {
path: string
schema: SchemaType
} ): Promise<z.infer<SchemaType>> { |
Beta Was this translation helpful? Give feedback.
Try this