【问题标题】:TypeScript and optional destructured argumentsTypeScript 和可选的解构参数
【发布时间】:2016-11-26 19:10:56
【问题描述】:

我似乎无法让可选参数与 TypeScript 中的解构参数一起使用。

为参数生成了正确的代码,但 Typescript 似乎不允许我在代码中使用生成的变量,这违背了目的。

我做错了吗?这是一个减少:

declare var lastDirectionWasDownish : boolean;

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

编译成

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


    【解决方案1】:

    TypeScript 实际上是在防止你犯在纯 JS 中会错过的错误。以下纯JS:

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

    TypeScript 了解这一点,并且不允许您使用 Node。要添加类型注释,您实际上会:

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

    修复

    你想要的

    function foo({root = document.activeElement } : {root: Node}) {
        root;// Okay
    }
    

    【讨论】:

    • 谢谢,这可能就是我想要的。这有点重复和冗长,但它确实有效!
    • JavaScript 选择 : 而不是 = 用于对象字面量(结构化)的赋值。这反过来又被重新用于解构。因此,我们将: 放在外部用于定义目的,因为没有一种干净的方式来插入它。
    猜你喜欢
    • 2023-04-04
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2019-06-28
    • 2022-07-24
    相关资源
    最近更新 更多