简体   繁体   中英

TypeScript and optional destructured arguments

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;
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM