typescript 在此函数上添加接口

ih99xse1  于 2022-12-30  发布在  TypeScript
关注(0)|答案(2)|浏览(113)

我正尝试在函数的this上添加类型,但我不确定如何执行此操作

interface ThisFunction{
    test:Function
}
function exampleFunction(){
//I want to add type of this to be of interface of ThisFunction like 
//I know that I will always bind the Test instance this should have interface as ThisFunction 
this.test();
}
//When I call the function
exampleFunction().bind({test: ()=>null})
4szc88ey

4szc88ey1#

您可以按如下方式键入this

interface ThisFunction {
  test: Function
}

function exampleFunction(this: ThisFunction) {
  this.test();
}

const boundExampleFunction = exampleFunction.bind({ test: () => null })

boundExampleFunction()

这段代码是安全的,因为TypeScript静态地检查this是否与其声明的类型匹配。例如,如果您试图在不绑定exampleFunction的情况下调用它,它将抛出一个错误。但是,如果您不想将未绑定的函数作为变量公开,您可以内联函数声明和bind操作:

interface ThisFunction {
  test: Function
}

const exampleFunction = (function (this: ThisFunction) {
  this.test();
}).bind({ test: () => null })

exampleFunction();
nwlls2ji

nwlls2ji2#

要输入this,我想您可以这样编写代码:

interface ThisFunction{
    test: Function
}
function exampleFunction(){
     const thing: ThisFunction = this
}

相关问题