Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript and optional destructured arguments

Tags:

typescript

I can't seem to get optional arguments works with destructured arguments in TypeScript.

The right code is generated for the argument, but Typescript doesn't seem to allow me to use the generated variables in my code, defeating the purpose.

Am I doing something wrong? Here is a reduction:

declare var lastDirectionWasDownish : boolean;

function goToNext(
    { 
        root: Node = document.activeElement, 
        actLikeLastDirectionWasDownish:boolean = lastDirectionWasDownish
    } = {}
) {
    return root && actLikeLastDirectionWasDownish;
}

which compiles into

function goToNext(_a) {
    var _b = _a === void 0 ? {} : _a, _c = _b.root, Node = _c === void 0 ? document.activeElement : _c, _d = _b.actLikeLastDirectionWasDownish, boolean = _d === void 0 ? lastDirectionWasDownish : _d;
    return root && actLikeLastDirectionWasDownish;
}
like image 448
FremyCompany Avatar asked May 25 '26 09:05

FremyCompany


1 Answers

TypeScript is actually preventing you from making a mistake that you would miss in pure JS. The following pure JS:

function foo({root: Node}) {
   // the parameter `root` has been copied to `Node`
}

TypeScript understands this and doesn't let you use Node. To add a type annotation you would actually:

function foo({root}: {root: Node}) {
   // now you can use `root` and it is of type Node
}

Fix

You want

function foo({root = document.activeElement } : {root: Node}) {
    root;// Okay
}
like image 110
basarat Avatar answered May 28 '26 00:05

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!