打字稿中上下文变量的典型化

Typification of context variable at typescript

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

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 方解决方案和 I无法更改它) 还有我的代码中广泛使用的方法,我想进行类型检查

您可以将 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 中有所介绍。