Skip to content

prefer-module-level-schema

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

Why

A schema created inside a function is rebuilt on each call. Module scope can enable reuse across callers; local schemas already support local type inference.

Fix

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

Examples

Before — flagged Do not rebuild a closed schema
src/handler.ts
import { z } from "zod";
export function handle(raw: unknown) {
const ZBody = z.object({ id: z.string(), name: z.string() });
return ZBody.parse(raw);
}
After — preferred Declare the schema once
src/handler.ts
import { z } from "zod";
const ZBody = z.object({ id: z.string(), name: z.string() });
export function handle(raw: unknown) {
return ZBody.parse(raw);
}

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"
}