Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zod - Using optional() with default() infers the wrong type

I'm using Zod with a field that is optional, but has a default value set, however, the inferred type says it could be undefined, even though it has a default value

const Schema = z.object({
  page: z.number().positive().optional().default(1)
})

type SchemaType = z.infer<typeof Schema>
// page?: number | undefined;

I tried using z.input and z.output, but they don't work either.

Is this intentional or is there another infer helper, which infers the parsed result?

like image 808
Diyan Slavov Avatar asked Jan 23 '26 12:01

Diyan Slavov


1 Answers

Have you enabled strict mode in your tsconfig.json? It's not enabled by default (the default value for --strict is false) but Zod's installation requirements say that it must be enabled:

  • TypeScript 4.5+!

  • You must enable strict mode in your tsconfig.json. This is a best practice for all TypeScript projects.

    // tsconfig.json
    {
      // ...
      "compilerOptions": {
        // ...
        "strict": true
      }
    }
    

On my machine, using your code and the latest version of Zod (v3.21.4), SchemaType is inferred as:

  • { page: number } when strict mode is enabled.
  • { page?: number } when strict mode is disabled.
like image 109
Matias Kinnunen Avatar answered Jan 26 '26 06:01

Matias Kinnunen