简体   繁体   English

使用点表示法时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"

I get this warning from tslint: 我从tslint得到这个警告:

Identifier 'foo' is never reassigned; 标识符'foo'永远不会被重新分配; use 'const' instead of 'let'. 使用'const'而不是'let'。 (prefer-const) (比较喜欢const的)

Funny though I don't get this warning in the second case with the variable snack . 虽然我没有在第二种情况下用变量snack得到这个警告,但很有趣。

I can get rid of this warning (which clutters my console when transcompiling) with /* tslint:disable: prefer-const */ 我可以用/* tslint:disable: prefer-const */去除这个警告(在转换时使我的控制台变得混乱) /* tslint:disable: prefer-const */

I haven't found any bug report on the tslint project . 我没有找到关于tslint项目的任何错误报告。 Since I'm new to typescript I'm wondering: Do I something wrong here? 由于我是打字稿的新手,我想知道:我这里有什么问题吗?

tslint is asking you to change let to const because the identifier foo is not reassigned. tslint要求您将let更改为const因为未重新分配标识符foo

The error can be removed by instead writing const : 可以通过编写const来删除错误:

const foo: obj = { bar: "" };
foo.bar = "hip";

Note that the const modifier just means you can't reassign the identifier: 请注意, const修饰符只是意味着您无法重新分配标识符:

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

It doesn't make the object itself readonly. 它不会使对象本身只读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM