3

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

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that is likely what I was looking for. That's a bit more repetitive and verbose, but it does work!
JavaScript chose : instead of = for assignment in object literals (structuring). That in turn was reused for destructuring. So we have : located externally for definition purposes as there isn't a clean way to plug it in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.