Search code examples
javascripttypescriptaggregationsubclassingforwarding

How to automatically forward class instance methods to another object's methods?


Regarding the following example code, is there any type-safe way of automatically forwarding any of the prototypal method calls, each to its related method of another object?

class Foo {
  greet() {
    return "hello";
  }
  sayGoodbye() {
    return "bye";
  }

  // ... many more methods
}

class Bar {
  foo: Foo;

  constructor() {
    this.foo = new Foo();
  }

  greet() {
    this.foo.greet();
  }

  sayGoodbye() {
    this.foo.sayGoodbye();
  }

  // ...
}

We don't have to write method() { foo.method() } for all methods on Foo? I.e. something like how in JavaScript we could do Object.getOwnPropertyNames(Foo.prototype).forEach(...) and point the methods to foo, but in a type-safe way?

I've tried mixins but I find those hard to work with since those invert the relationship (Foo has to subclass Bar, so I can't e.g. instantiate Foo with specific parameters when declaring Bar).


Solution

  • You can use the extends keyword to create a subclass which inherits from its superclass:

    The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.

    TS Playground

    class Foo {
      greet() {
        return "hello";
      }
      sayGoodbye() {
        return "bye";
      }
    }
    
    class Bar extends Foo {}
    //        ^^^^^^^
    
    const bar = new Bar();
    
    console.log(bar.greet()); // "hello"
    console.log(bar.sayGoodbye()); // "bye"