-1

I have the following code

const myVariable: number | undefined;

if (someCondition) {
     const { someAttribute, anotherAttribute } = someFunction(); //here I want to assign directly that myVariable to someAttribute. 
     doAnotherTask(anotherAttribute);
  
}

doSomethingWithVariable(myVariable);

How can I destruct someFunction to get someAttribute and directly assign myVariable to it.

const {someAttribute: myVariable} wouldnt work here, since myVariable is defined outside the scope of the condition.

AngularDebutant
  • 1,436
  • 5
  • 19
  • 41

1 Answers1

0

Just drop the const, since you're not creating a new variable. And myVariable can't be a const since you need to assign a value to it later.

Due to how the JavaScript language works, you also need parentheses around the destructuring statement.

let myVariable: number | undefined;

if (someCondition) {
     ({ someAttribute: myVariable } = someFunction());
}

doSomethingWithVariable(myVariable);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • Maybe it's better to declare a `let someAttibute`outside, otherwise you have a `var` – mgm793 Apr 26 '22 at 13:34
  • 1
    @mgm793 no, `someAttribute` is not used and not defined, it's just name of the property and not a variable – Christian Vincenzo Traina Apr 26 '22 at 13:36
  • Note you need parentheses when trying to destructure to an existing variable: https://tsplay.dev/N7OdPN – jonrsharpe Apr 26 '22 at 13:37
  • What if I want to add another property from `someFunction` to the descrtruction and use it somewhere else? see my updated question. – AngularDebutant Apr 26 '22 at 13:38
  • 1
    @AngularDebutant you need to be defining _all_ or _none_ of the destructured variables. – jonrsharpe Apr 26 '22 at 13:40
  • @AngularDebutant If you want to use a property outside of the if-block scope, then you'll need to have a `let` variable declaration at the top and do the same thing. Alternatively you can use `var` with a second destructuring statement, though `var` would be seen as a codesmell since we're way past the introduction of `let` and `const` – Samathingamajig Apr 26 '22 at 13:42
  • @Samathingamajig what if I want to use the second property inside the if statement? – AngularDebutant Apr 26 '22 at 13:44
  • The you would either declare a new variable with `let` inside the `if` but before the destructuring, or you would store the direct value of the function call and perform two destructures. – Samathingamajig Apr 26 '22 at 13:45