Home > Software design >  How to define "this" type in a binded function
How to define "this" type in a binded function

Time:10-26

I have a question, lets say I have the following code

class MyClass {
    constructor() {}

    func(fn: () => any) {
        fn.bind(this)()
    }
}

So in this scenario, how would I tell the fn function that this the type MyClass using typescript?

CodePudding user response:

If the first parameter of a function is named this, then the type of that parameter will be used as the type of this:

class MyClass {
    constructor() {}

    func(fn: (this: MyClass) => any) {
        fn.bind(this)()
    }
}

See Declaring "this" in functions

Playground

  • Related