Home > Software design >  Is there a way to set the type of `this` on an interface?
Is there a way to set the type of `this` on an interface?

Time:11-08

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...

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?

CodePudding user response:

You can specify a this parameter to the callback type:

interface Config {
  id: string
  onOpen?: (this: Foo) => void
}
  • Related