Skip to content

prefer-module-level-constant

Hoist literal-only constant collections and regexes out of function bodies to module scope so they are allocated once.

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.

Examples

Before — flagged Do not recreate a constant collection
src/keys.ts
function isAllowed(key: string) {
const KEYS = ["a", "b", "c"];
return KEYS.includes(key);
}
After — preferred Hoist a constant collection
src/keys.ts
const KEYS = ["a", "b", "c"] as const;
function isAllowed(key: string) {
return KEYS.includes(key);
}

Options

{
"additionalProperties": false,
"properties": {
"checkRegex": { "type": "boolean" },
"ignoreTestFiles": { "type": "boolean" },
"minElements": { "minimum": 1, "type": "number" }
},
"type": "object"
}