Search code examples
javascripttypescriptcompositionfunction-composition

TypeScript class A's method to work as a pass-through to a B's method


I am trying to wrap a third-party library auth0-js into my own class. In the example below an Authentication class from Auth0.js is being wrapped and is used as the implementation for the pass-through methods. See how buildLogoutUrl(options) does nothing more than invoking a function on the wrapped object.

Is there a more concise way to "redirect" Authentication's buildLogoutUrl(...) to wa's buildLogoutUrl(...) without using inheritance?

import * as a0 from "auth0-js";

export class Authentication {

  constructor(private wa: a0.Authentication) { }

  buildLogoutUrl(options?: a0.LogoutOptions | undefined): string {
    return this.wa.buildLogoutUrl(options);
  }

  // Many other methods...

}

Solution

  • At the expensive of flexibility, you can save yourself a little bit of typing by using an assignment:

    import * as a0 from "auth0-js";
    
    export class Authentication {
    
      constructor(private wa: a0.Authentication) { }
    
      buildLogoutUrl = this.wa.buildLogoutUrl;
    
    }
    

    By "flexibility", I mean that you can't change the function signature or perform any pre-processing on the arguments, for example. Also your class no longer has a fixed public interface that you control (imagine that the author of the library changes the function signature).