Fraser Orr
Fraser Orr

Reputation: 425

Let typescript know what type an object is

I am writing a library that allows user to specify a callback. Like this:

interface IParams {
  context: any;
  okCallback: (value: string) => void
  ... etc ...
}

class MsgBox {
   static getInput(params: IParams) {
      ....
      okCallback.call(params.context, value);
   }
}

The purpose of the context is to put the callback in a context. So for example I can do this:

MsgBox.getInput({
     context: this,
     okCallback(value) {
        this.accessToEnclosingClass
     }
}

Since the callback needs access to properties of the calling class. This makes it more convenient than using $.proxy() all over the place.

This works correctly, however, the problem is with the typescript compiler. Within the callback typescript does not know the type of this, and so treats it like any, and doesn't do any type checking for me, something which has lead to a lot of frustration.

Is there a way to let Typescript compiler know what the type of this is in this context? I can do:

     okCallback(value) {
        const self = this as EnclosingClassType;
        self.accessToEnclosingClass
     }

Which does work, but I'd rather use this (because otherwise there is an opportunity for accidentally using this, leading to possible non compile type type errors.

Of course this is a simple example, the challenge happens when okCallback is not defined in this context, but as a separate function.

Any suggestions or thoughts on this?

Upvotes: 0

Views: 210

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164427

You can just use an arrow function which saves the context of this:

MsgBox.getInput({
     context: this,
     okCallback: (value) => {
        this.accessToEnclosingClass
     }
}

The compiler (and IDE) will understand that as well and so won't treat this as any.

Upvotes: 1

Related Questions