FremyCompany
FremyCompany

Reputation: 2840

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

Upvotes: 3

Views: 2154

Answers (1)

basarat
basarat

Reputation: 276259

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
}

Upvotes: 7

Related Questions