Artrix
Artrix

Reputation: 169

How to define "this" type in a binded function

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?

Upvotes: 0

Views: 77

Answers (1)

tenshi
tenshi

Reputation: 26326

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

Upvotes: 1

Related Questions