TypeScript · performance
prefer-module-level-constant
eslint:prefer-module-level-constant Hoist literal-only constant collections and regexes out of function bodies to module scope so they are allocated once.
- Default
- error
- Fix
- none
- Languages
- typescript
Why
Recreating immutable lookup data on every call wastes allocations and obscures its constant nature.
Fix
Declare immutable literal collections and non-stateful regular expressions once at module scope.
Before / after
Executed by this rule’s unit tests.
Before
Do not recreate a constant collection
function isAllowed(key: string) { const KEYS = ['a', 'b', 'c']; return KEYS.includes(key); } After
Hoist a constant collection
const KEYS = ['a', 'b', 'c'] as const; function isAllowed(key: string) { return KEYS.includes(key); } Limits
- Collections that are small, mutated, escape the function, or depend on local values are not reported.
Message IDs
hoistCollectionhoistRegex