Sunday, May 13, 2018

Destructuring to existing variables

Can't be done like this:

function getColor(): { a: number, b: string }
{
    return { a: 0xff0000, b: "Red" };
}

let color: number;
let colorString: string;

{ a: color, b: colorString } = getColor();

window.alert(color);
window.alert(colorString);

Must be done like this, use parenthesis. As for why: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

function getColor(): { a: number, b: string }
{
    return { a: 0xff0000, b: "Red" };
}

let color: number;
let colorString: string;

({ a: color, b: colorString } = getColor());

window.alert(color);
window.alert(colorString);


Happy Coding!

No comments:

Post a Comment