Javascript typescript上上下文变量的类型化
我有几个助手函数,它们被合并到容器对象中。函数可以在代码的任何地方调用Javascript typescript上上下文变量的类型化,javascript,typescript,typescript-typings,Javascript,Typescript,Typescript Typings,我有几个助手函数,它们被合并到容器对象中。函数可以在代码的任何地方调用 const Utils = { isSomeMethod: function (a: INodeType, b: INodeType) { // Some logic }, _nodeCheck: function (n: INodeType) { // `this` : { // node: INodeType, //
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));
},
...
}
该函数可以接受参数和上下文变量此
我有一个问题,是否可以将任何特定类型设置为上下文变量
注意:在上面的示例中方法
\u nodeCheck
必须使用类型为{node:INodeType,nn:INodeType}
的上下文变量(该第三方解决方案和我无法更改它)另外,该方法在我的代码中广泛使用,我希望进行类型检查您可以将此的类型指定为函数的额外参数。此参数不会发送到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}
这在文档中有介绍。@t-j-crowder 10x供文档参考