8000 v4: Type violation upon piping into coerced types · Issue #4236 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
v4: Type violation upon piping into coerced types #4236
Closed
@martinjlowm

Description

@martinjlowm

edit: supposedly, this is covered in the migration announcement: https://v4.zod.dev/v4/changelog#zcoerce-updates

Testing out v4 I stumbled upon a chain piping into z.coerce.date().

const date = z.union([z.string(), z.number(), z.date()]).nullish().transform((v) => (v === null ? undefined : v)).pipe(z.coerce.date().default(() => new Date()))

Results in,

typescript [2345]: Argument of type 'ZodCoercedDate' 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'.

The intention with this was to accept string | number | Date | null | undefined, map null -> undefined and convert undefined -> Date through the default call such that null and undefined would be converted to the current time.

Seeing this error made me think... and I ended up simplifying it with:

const date = z.null().transform(() => new Date()).or(z.coerce.date())

Handling null first and then afterwards coercing the rest. That being said, v3 typed the pipe correctly without errors, but it may overcomplicate things.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0