Angular/Typescript lint错误使"let"为"const"

Ant*_*der 3 angular

在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;
      }
    }
Run Code Online (Sandbox Code Playgroud)

让钥匙 - 给出ts lint错误

我喜欢继续"让"类型

Arm*_*yan 12

那么,这就是为什么你应该const在这里使用而不是let.const,当声明复合对象时,表示该对象无法重新分配给对象的另一个引用.

const arr = [];
arr = [1,2,3]; // will throw an error!
Run Code Online (Sandbox Code Playgroud)

但这并不意味着你无法改变对象的内部结构:

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
Run Code Online (Sandbox Code Playgroud)

TSLint使用的策略要求您使用,const而不是let如果您有一个在声明后永远不会被重新分配的值.这种方法没有缺点.一个好的观点是,稍后处理您的代码的人现在将该数组重新分配给新值是一个坏主意,并且您依赖于该数组未被重新分配.如果您使用let某人可能很容易更改阵列指向其他东西,可能会破坏您的代码.为了保持一致性,我们总是使用关键字声明这些变量const.

如果您真的只想使用let,评论中提供了解决方法,但我强烈建议您坚持使用标准,因为这不是一个好主意.