Issue
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.
Solution
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);
Answered By - Samathingamajig
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.