angulartypescriptangular18

How to reassign multiple let variable in angular 18


How to reassign multiple let values in angular18

    let one,two,three; 
    let fun=()=> {
      return ({one: "tt", two:"uu", three: "vv"})
    }
   

Demo:https://stackblitz.com/edit/angular-ivy-pzes9v?file=src%2Fapp%2Fapp.component.ts


Solution

  • This is a typescript thing, not linked to angular.

    const values = {one: "tt", two:"uu", three: "vv"};
    let one;
    let two;
    let three;
    console.log(values);
    ({one, two, three} = values);
    console.log(one);
    console.log(two);
    console.log(three);
    

    You need to add parenthesis around your destructuring assignment.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    Also note that your values is never set, which won't work

    in your example:

     ngOnInit(): void {
         let one;
         let two;
         let three; 
         let values = {one: "tt", two:"uu", three: "vv"};
       
         ({one,two,three} = values);
     
         console.log(one);
         console.log(two);
         console.log(three);
     }
    

    or with a function

      ngOnInit(): void {
         let one, two, three;
         let fun = () => {
           return { one: 'tt', two: 'uu', three: 'vv' };
         };
    
         ({ one, two, three } = fun());
    
         console.log(one);
         console.log(two);
         console.log(three);
      }