1

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

1
  • Object.getOwnPropertyNames(Foo.prototype).forEach(...) is a totally type-safe approach for implementing forwarding, based on an aggregated property, in a generic way. Or do you mean, you are looking for a TypeScript yoga/gymnastics-figure which is capable of expressing such a pattern? Commented Jan 22 at 12:13

1 Answer 1

0

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"

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.