Skip to content

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

src/keys.ts · focus
function isAllowed(key: string) { const KEYS = ['a', 'b', 'c']; return KEYS.includes(key); }

After

Hoist a constant collection

src/keys.ts · focus
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

Options

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