Skip to content

TypeScript · performance

prefer-module-level-schema

eslint:prefer-module-level-schema

Declare a Zod schema at module scope when it closes over nothing in the enclosing function

Default
error
Fix
none
Languages
typescript

Why

A closed schema created inside a function is rebuilt on every call and cannot be reused or exported for inference.

Fix

Move the closed schema declaration to module scope and reference it from the function.

Before / after

Executed by this rule’s unit tests.

Before

Do not rebuild a closed schema

src/handler.ts · focus
import { z } from 'zod'; export function handle(raw: unknown) { const ZBody = z.object({ id: z.string(), name: z.string() }); return ZBody.parse(raw); }

After

Declare the schema once

src/handler.ts · focus
import { z } from 'zod'; const ZBody = z.object({ id: z.string(), name: z.string() }); export function handle(raw: unknown) { return ZBody.parse(raw); }

Limits

  • Schemas that depend on local state or are wrapped in a recognized memoization helper are excluded.

Message IDs

hoistSchema

Options

{
  "additionalProperties": false,
  "properties": {
    "factories": {
      "description": "Zod factory names to check. Defaults to the object-like composites; add `array` / `enum` to widen.",
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "ignoreTestFiles": {
      "description": "Skip test files, where a fixture schema belongs next to its assertion.",
      "type": "boolean"
    },
    "memoCallees": {
      "description": "Wrappers that construct their callback at most once. Defaults to lazy, memo, once, and useMemo.",
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "minProperties": {
      "description": "Minimum key count before an object-like schema is reported.",
      "minimum": 0,
      "type": "number"
    }
  },
  "type": "object"
}