简体   繁体   English

Angular / Typescript lint错误使“let”为“const”

[英]Angular/Typescript lint error to make “let” as “const”

In Angular with typescript, how to create a empty array and push the values in it, 在Angular with typescript中,如何创建一个空数组并推送其中的值,

 @Pipe({name: 'keys'})
    export class KeysPipe implements PipeTransform {
      transform(value, args:string[]) : any {
        let keys = [];
        for (let key in value) {
          keys.push({key: key, value: value[key]});
        }
        return keys;
      }
    }

let keys - Giving ts lint error 让钥匙 - 给出ts lint错误

I like to continue with "let" type 我喜欢继续“让”类型

Well, here is why you should use const here instead of let . 那么,这就是为什么你应该在这里使用const而不是let const , when declaring compound objects, indicates, that the object cannot be reassigned to another reference of an object. const ,在声明复合对象时,表示该对象无法重新分配给对象的另一个引用。

const arr = [];
arr = [1,2,3]; // will throw an error!

But it does not mean you cannot change the internal structure of the object: 但这并不意味着你无法改变对象的内部结构

const arr = [];
arr.push(1) // see, the array internally is changes, it is now [1], but the reference didn't change. so this is completely okay

TSLint uses a policy which requires you to use const rather then let if you have a value that is never being reassigned after its declaration. TSLint使用一个策略,要求你使用const而不是let你拥有一个在声明之后永远不会被重新赋值的值。 There are no downsides to this approach. 这种方法没有缺点。 A good point is that someone working on your code later will now that reassigning that array to a new value is a bad idea and that you depend on that array not being reassigned. 一个好的观点是,稍后处理您的代码的人现在将该数组重新分配给新值是一个坏主意,并且您依赖于该数组未被重新分配。 If you use let someone may easily change the array to point to something else, possibly breaking your code. 如果您使用, let某人可以轻松地将数组更改为指向其他内容,可能会破坏您的代码。 For consistency we always declare such variables with the keyword const . 为了保持一致性,我们总是使用关键字const声明这些变量。

If you really just want to use let , workaround was provided in the comments, but I strongly suggest you stick with the standard, as this is not a good idea. 如果你真的只想使用let ,那么评论中会提供解决方法,但我强烈建议你坚持使用标准,因为这不是一个好主意。

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

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