打字稿隐藏超类的道具

und*_*ned 5 javascript typescript

我有一个扩展另一个类的类。例如:

class Store extends BehaviorSubject {
  constructor(obj) {
     super(obj)
  }
}
Run Code Online (Sandbox Code Playgroud)

我还有更多的类 extends Store。我需要的是一种从BehaviorSubject超类中隐藏某些属性的next()方法,例如方法。

class SomeStore extends Store {

}

// I want to hide from this class some methods, properties
// That exists on the BehaviorSubject class. 
const s = new SomeStore();
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Thi*_*ala 5

不可以。您可以覆盖子类中的方法来做其他事情(或什么都不做),但这违反了 Liskov 替换原则。

如果您的 Store 类不是 BehaviorSubject,并且不像一个 BehaviorSubject,那么扩展是不正确的。在这种情况下,Store 应该包含一个 BehaviorSubject 的私有实例,如果有必要,通过“代理”它们来公开它的一些方法/属性。