Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to set the type of `this` on an interface?

I’m writing a TypeScript declaration file for a vanilla JS library. The main function takes a config argument that can contain functions, like this:

interface Config {
  id: string
  onOpen?: () => void
}

All of the properties from config are added to an object main function of another type, Foo:

interface Foo {
  someKey: number,
  onOpen: () => void // Set to the onOpen function passed to mainFunction
}


function mainFunction(config: Config): Foo

Since the functions from config are only called within the context of the Foo object, the this keyword should be in the scope of Foo. This means that the following were passed to mainFunction

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mainFunction({
  id: 'abc',
  onOpen: function () {
    alert(this.someKey)
  }
})

this.someKey would be retrieved from the Foo object.

Is there a way to say that any functions on the interface Config with have this keyword of type Foo?

>Solution :

You can specify a this parameter to the callback type:

interface Config {
  id: string
  onOpen?: (this: Foo) => void
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading