Search code examples
typescriptkurento

How to type define a bound this


I'm using a library with a function that takes a callback, and then (frustratingly) calls callback = (callback || noop).bind(this). In the callback, I need to grab this:

    kurento_utils.WebRtcPeer.WebRtcPeerSendonly(options, function (error: any) {
        if ( error ) {
            return on_error(error);
        }
        let webRTC_peer = this;  // kurento_utils binds 'this' to the callback
                       // ^^^^ error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. 

        webRTC_peer.generateOffer((error: string | undefined, offer: string) => {

...

TypeScript is (understandably) unhappy with this situation, at least when the noImplicitThis flag is enabled.

I have no idea how to properly type annotate this.


Solution

  • You can add a this parameter to the function. This parameter will not be emitted to Javscript, and will be just for the benefit of the compiler so it can correctly type this witing the function:

     kurento_utils.WebRtcPeer.WebRtcPeerSendonly(options, function (this:WebRtcPeer, error: any) {
          let webRTC_peer = this; // this will be of type WebRtcPeer
     }      
    

    Or if you also control the WebRtcPeerSendonly you could specify that the function it takes as a parameter will have a certain this passed to it and type inference will work for this just as any other parameter:

    class WebRtcPeer {
        WebRtcPeerSendonly(options: any, fn: (this: WebRtcPeer, error: any) => void) {
    
        }
    }
    
    new WebRtcPeer().WebRtcPeerSendonly({}, function(error){
        let webRTC_peer = this; // this will be of type WebRtcPeer
    })