使用点表示法时 tslint prefer-const 警告

tslint prefer-const warning when using dot notation

interface obj {
  bar: string
}

function randomFunction() {
  let foo: obj = { bar: "" }
  foo.bar = "hip"
}

let snack: obj = { bar: "" }
snack.bar = "hop"

我从 tslint 收到此警告:

Identifier 'foo' is never reassigned; use 'const' instead of 'let'. (prefer-const)

有趣的是,在第二种情况下,变量 snack.

我没有收到此警告

我可以用 /* tslint:disable: prefer-const */

我没有在 tslint project 上找到任何错误报告。 由于我是打字稿的新手,我想知道:我这里有什么问题吗?

tslint 要求您将 let 更改为 const,因为标识符 foo 未重新分配。

可以通过写入 const:

来消除错误
const foo: obj = { bar: "" };
foo.bar = "hip";

请注意,const 修饰符仅表示您无法重新分配标识符:

 const foo = { bar: "" };
 foo = { bar: "" }; // error

它不会使对象本身变为只读。