我正在探索使用TypeScript实现一个类的可能性。
因此,我编写了以下代码Playground链接:
class A {
private f() { console.log("f"); }
public g() { console.log("G"); }
}
class B implements A {
public g() { console.log("g"); }
}
我遇到了错误:Class 'B' incorrectly implements class 'A' --- property 'f' is missing in type 'B'
,并且建议我实际上是想使用extends
。
因此我尝试创建一个名为f
的私有字段(public
无法识别它们具有不同的访问修饰符)Playground链接。
现在我收到错误: Class 'B' incorrectly implements class 'A'. Types have separate declarations of a private property 'f'
。这让我很困惑:
- 为什么私有成员如此重要-如果我使用不同的数据结构实现相同的算法,我是否必须声明相同的内容,以便进行类型检查?
- 为什么当我将
f
实现为私有函数时会出现错误?
实际上我不会在实践中这样做,但是我对TS为什么会像这样工作感到好奇。
谢谢!
implements
的行为。@Igor,我不想那样 :) - Radu Szasz