Skip to content

TypeScript build fails with exactOptionalPropertyTypes: true due to Zod .optional().default() pattern #21

@hl9020

Description

@hl9020

Description

The project's tsconfig.json enables exactOptionalPropertyTypes: true, but many tool schemas use z.something().optional().default(value) patterns. This combination causes TypeScript compilation errors because exactOptionalPropertyTypes requires undefined to be explicitly included in union types for optional properties.

Error Example

error TS2375: Type '{ ... }' is not assignable to type '...' with 'exactOptionalPropertyTypes: true.
  Consider adding 'undefined' to the type of the target.

This affects numerous tool definitions across the codebase (application, backup, domain, mysql, postgres tools etc.) wherever .optional().default() is used.

Root Cause

With exactOptionalPropertyTypes: true, TypeScript distinguishes between "property is missing" and "property is undefined". Zod's .optional() generates a type like string | undefined, but the resulting TypeScript type for the object property doesn't satisfy the stricter check when combined with .default().

Workaround

Set exactOptionalPropertyTypes: false in tsconfig.json. This allows npm run build to succeed.

Possible Fixes

  1. Change tsconfig (quick fix): Set exactOptionalPropertyTypes: false — this is the simplest approach and doesn't affect runtime behavior
  2. Fix Zod schemas (proper fix): Adjust schemas to be compatible with strict optional property types, e.g. using explicit z.union([z.string(), z.undefined()]) instead of z.string().optional()

Environment

  • TypeScript 5.x with strict: true and exactOptionalPropertyTypes: true
  • Zod v3
  • Node.js 20+

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions