zod icon indicating copy to clipboard operation
zod copied to clipboard

Functions with transform in returns/args

Open gbouteiller opened this issue 1 year ago • 1 comments

Hello and first of all, thank you for this great library.
I'm trying to validate a function with a schema with a returns that contains a transform. The problem occurs when the function schema is implemented : the return type is Returns['_input'] instead of Returns['_output']. Here is a simple example :

const a = z.function().args(z.string()).returns(z.number().transform((v) => `${v}`));
const b = a.implement((e) => +e); // b is (e:string) => number but should be (e:string) => string

By investigating, I guess the problem comes from https://github.com/colinhacks/zod/blob/master/src/types.ts (lines 2884-2894) where the return types of implement and strictImplement are not accurate :

implement<F extends InnerTypeOfFunction<Args, Returns>>(func: F): F {
    const validatedFunc = this.parse(func);
    return validatedFunc as any;
}

strictImplement(func: InnerTypeOfFunction<Args, Returns>): InnerTypeOfFunction<Args, Returns> {
    const validatedFunc = this.parse(func);
    return validatedFunc as any;
}

I guess they should match the OuterTypeOfFunction defined in the same file at line 2752.

gbouteiller avatar Jul 05 '22 17:07 gbouteiller

In addition, the problem is the same for the args for the same reason :

const a = z.function().args(z.string().transform((v) => +v).returns(z.number().transform((v) => `${v}`));
const b = a.implement((e) => +e); // b is (e:number) => number but should be (e:string) => string

gbouteiller avatar Jul 05 '22 17:07 gbouteiller

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.

stale[bot] avatar Sep 03 '22 17:09 stale[bot]

Fixed in 3.18

colinhacks avatar Sep 06 '22 07:09 colinhacks