Typescript- 使用 class 作为接口,为什么我必须实现私有 members/methods?

Typescript- Using class as interface, why do I have to implement private members/methods?

我正在使用 Mixin 模式,如下图所示。为什么 Typescript 要求您在目标 class 中为 mixin class 的 private 属性提供替代属性 (A)?它对于 public 属性完全有意义,但对于私有属性,它不必要地通过要求将目标 class 与 mixin class 的内部实现细节一起删除在目标 class 中。似乎 Typescript 转译器应该不需要这个。

class Mixin {
    private foo:string;
}

class A implements Mixin {
   // stand-in properties, typescript requires even
   // private properties to be stubbed-out 
   foo:string;
}

私有成员对 TypeScript 中类型的结构有贡献,因此如果您不实现它们,您将与该类型不兼容。这实际上使得在 TypeScript 中无法在结构上匹配具有私有成员的类型,因为您是:

一个。未能提供类型

b。提供私有成员的单独实现

所以你只能extend一个带有私有成员的类型,而不是implement它。

考虑到这一点,您最好不要将私有成员与混入一起使用。在实现中提供 ghost-members class 并祈祷如果 mixins 获得一些牵引力,ghosting 将变得不必要(参见 TypeScript mixins part one)。