I am trying to add the type on this of the function but I am not sure how I can do it
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})
CodePudding user response:
You can type this
like that:
interface ThisFunction {
test: Function
}
function exampleFunction(this: ThisFunction) {
this.test();
}
const boundExampleFunction = exampleFunction.bind({ test: () => null })
boundExampleFunction()
This code is safe because TypeScript statically checks that this
matches its declared type. For example it will throw an error if you try to call exampleFunction
without binding it. However, you could inline the function declaration and the bind
operation if you don't want to expose the unbound function as a variable:
interface ThisFunction {
test: Function
}
const exampleFunction = (function (this: ThisFunction) {
this.test();
}).bind({ test: () => null })
exampleFunction();
CodePudding user response:
To type this
, I think you could code it like that:
interface ThisFunction{
test: Function
}
function exampleFunction(){
const thing: ThisFunction = this
}