zod icon indicating copy to clipboard operation
zod copied to clipboard

v4: piping to coerce (type error)

Open RobinTail opened this issue 8 months ago • 2 comments

I'm currently trying to migrate to Zod 4.

Noticed an issue with the following schema:

z.string().regex(/\d+/).pipe(z.coerce.number())

That has the following type error:

TS2345: Argument of type ZodCoercedNumber is not assignable to parameter of type $ZodType<any, string>
The types of _zod.input are incompatible between these types.
Type unknown is not assignable to type string

To me it's not critical, it's just a part of my test for pipes, but it may be an issue for others. I presume it's because the input of coerced types became unknown instead of any

RobinTail avatar Apr 11 '25 07:04 RobinTail

Though, it can be possibly worked around by doing a transformation ahead, but without coercion in the pipe

z.string().regex(/\d+/).transform(Number).pipe(z.number())

RobinTail avatar Apr 11 '25 07:04 RobinTail

Found out that .transform() in Zod 4 already makes ZodPipe instance, so another .pipe() is probably redundant

RobinTail avatar Apr 11 '25 09:04 RobinTail

A bit late to the party, but I fixed it like this: memory: z.coerce.number().min(1) as unknown as z.ZodNumber,

thaoms avatar Oct 07 '25 08:10 thaoms