使"let"变角的Angular/Typescript棉绒错误作为"const", [英] Angular/Typescript lint error to make "let" as "const"
问题描述
在带有打字稿的Angular中,如何创建一个空数组并将其值压入其中,
In Angular with typescript, how to create a empty array and push the values in it,
@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键-出现ts lint错误
let keys - Giving ts lint error
我想继续使用"let"类型
I like to continue with "let" type
推荐答案
好,这就是为什么您应该在此处使用const
而不是let
的原因.声明复合对象时,const
表示该对象无法重新分配给该对象的另一个引用.
Well, here is why you should use const
here instead of let
. const
, when declaring compound objects, indicates, that the object cannot be reassigned to another reference of an object.
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使用的策略要求您使用const
而不是let
,如果您拥有一个在声明之后再也不会重新分配的值.这种方法没有任何缺点.很好的一点是,稍后有人在处理您的代码将使该数组重新分配为新值是一个坏主意,并且您依赖于未重新分配该数组.如果使用let
,则可能会轻易地将数组更改为指向其他对象,这可能会破坏您的代码.为了保持一致,我们始终使用关键字const
声明此类变量.
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. 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. For consistency we always declare such variables with the keyword const
.
如果您真的只想使用let
,则注释中提供了解决方法,但是我强烈建议您坚持使用标准,因为这不是一个好主意.
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"变角的Angular/Typescript棉绒错误作为"const",的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!