'Destruct and assign in javascript/typescript [duplicate]
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 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
