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