4

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

4
  • yes, because for each iteration the value of key is not changing. In that case, you should use const Commented Jan 10, 2018 at 11:02
  • set "prefer-const": false in tslint config Commented Jan 10, 2018 at 11:03
  • @callback: I want to know why we shouldn't use "let" here. and problem "keys" not the "key" Commented Jan 10, 2018 at 11:29
  • @Aravind: looking for a direct answers instead of workaround. Commented Jan 10, 2018 at 11:30

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly!! What I need. Thank you:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.