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 keys - Giving ts lint error
I like to continue with "let" type
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 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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With