close

prefer-const

Added in v0.3.3

Configuration

PresetConfigured Value
✅ ts.configs.recommended"error"
✅ ts.configs.recommendedTypeChecked"error"
✅ ts.configs.strict"error"
✅ ts.configs.strictTypeChecked"error"
✅ ts.configs.stylistic"error"
✅ ts.configs.stylisticTypeChecked"error"
rslint.config.ts
import { defineConfig, js } from '@rslint/core';

export default defineConfig([
  js.configs.recommended,
  {
    rules: {
      'prefer-const': 'error',
    },
  },
]);

Rule Details

Requires const declarations for variables that are never reassigned after declared. If a variable is never reassigned, using the const declaration is better because it makes the intent clear that the value is not intended to be changed.

Examples of incorrect code for this rule:

let x = 1;
let obj = { key: 0 };
for (let x in obj) {
  console.log(x);
}
for (let x of [1, 2, 3]) {
  console.log(x);
}

Examples of correct code for this rule:

const x = 1;
const obj = { key: 0 };
let y = 1;
y = 2;
let z;
z = 1;
for (const x in obj) {
  console.log(x);
}
for (const x of [1, 2, 3]) {
  console.log(x);
}

A global named by an /* exported name */ block comment is shared with the other scripts loaded alongside this one, any of which may reassign it, so the rule leaves such a declaration alone:

/* exported sharedValue */
let sharedValue = 1;

Original Documentation