【问题标题】:Typification of context variable at typescript打字稿中上下文变量的类型化
【发布时间】:2018-10-17 00:06:56
【问题描述】:

我有一些辅助函数被合并到容器对象中。并且可以从代码中的任何位置调用这些函数。

const Utils = {
    isSomeMethod: function (a: INodeType, b: INodeType) {
         // Some logic
    },

    _nodeCheck: function (n: INodeType) {
        //  `this` : {
        //      node: INodeType,
        //      nn: INodeType,   
        //  }

        return (n !== this.node && Utils.isSomeMethod(n, this.nn));
    },

    ...
}

该函数可以接受参数以及上下文变量this我有一个问题是否有可能将任何特定类型设置为context variable

注意:在上面的示例中,方法 _nodeCheck 必须采用类型为 {node: INodeType, nn: INodeType} 的上下文变量(该第 3 方解决方案,我无法更改它)该方法在我的代码中广泛使用,并且我想要进行类型检查

【问题讨论】:

    标签: javascript typescript typescript-typings


    【解决方案1】:

    您可以将this 的类型指定为函数的额外参数。此参数不会发送到 JavaScript,只会用于类型检查。

    const Utils = {
        isSomeMethod: function (a: INodeType, b: INodeType) {
             // Some logic
        },
    
        _nodeCheck: function (this: {node: INodeType, nn: INodeType}, n: INodeType) {
            // This as the type specified above and is checked.
            return (n !== this.node && Utils.isSomeMethod(n, this.nn));
        },
    
        ...
    }
    let node!: INodeType;
    Utils._nodeCheck(node) // not allowed this (aka Utils) is not assignable to {node: INodeType, nn: INodeType}
    

    这在文档here 中有介绍。

    【讨论】:

    • @t-j-crowder 10x 供文档参考
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2021-04-19
    • 2017-06-10
    • 1970-01-01
    • 2018-05-06
    相关资源
    最近更新 更多