如何在不更改基类方法/属性的情况下公开它?

时间:2020-09-22 17:02:28

标签: typescript inheritance typescript-generics

拥有

export class CrudService<T> {
  constructor(...) {}

  protected index$: Observable<T[]> = ...
  protected delete(id: string) { ... }
  protected update(id: string, obj: T) { ... }
  protected create(obj: T) { ... }
}

和具体的类,例如:

interface Message {
  from: string;
  to: string;
  body: string;
}

export class MessageService extends CrudService<Message> {
  constructor(...) { super(...); stuff() }
  
  public index$ = super.index$;  // Results in null
  public index$; // Results in loss of type information (update: any)
}

如何用最少的样板简单地公开基本方法,而无需修改实现?

1 个答案:

答案 0 :(得分:0)

我不确定您的意思,但我会尽力回答。 假设您具有以下层次结构:

abstract class Base() {
 
   constructor() {}

   someMethod() {
       //boiler plate code
          ...
          ...

       this.abstrMethod();
   }

   abstract abstrMethod();
}

class Concrete extends Base() {
   constructor() { super() }

   abstrMethod() { /*concrete implementation*/ };
}

这里someMethod()在调用abstrMethod()将要实现的Concrete之前有其自己的实现。这样可以暴露Base.someMethod()的样板,但也可以使其与abstrMethod()多态。