Search code examples
typescriptzod

Property 'gt' does not exist on type 'ZodEffects<ZodNumber, number, unknown>'.ts(2339)


I am trying to use zod to preprocess String before coerce it into Number.

const serviceCostSchema = z
  .preprocess((val) => Number(String(val).replace(/^0(\d+)/, "$1")), z.number())
  .gt(0, { message: "Service cost must be greater or equal to zero." });

I received this error

Property 'gt' does not exist on type 'ZodEffects<ZodNumber, number, unknown>'.ts(2339)

How should I re-write to get what I want


Solution

  • You can't chain off of the return value of preprocess. Instead, just add that to the schema that you pass in as the second argument:

    const serviceCostSchema = z.preprocess(
      (val) => Number(String(val).replace(/^0(\d+)/, "$1")),
      z.number().gt(0, {
        message: "Service cost must be greater or equal to zero."
      })
    )