Typescript - 重载私有方法
Posted
技术标签:
【中文标题】Typescript - 重载私有方法【英文标题】:Typescript - Overloading private method 【发布时间】:2015-09-07 12:36:41 【问题描述】:你好我想实现这个场景:
class A implements InterfaceForA
a():void
this.b();
Class B extends A
private b():void
console.log('Hi');
但它会抛出:
错误 TS2339:类型“A”上不存在属性“b”。
所以我更新了我的课程,现在它抛出了:
错误 TS2415:“B”类错误地扩展了基类“A”。类型具有私有属性“b”的单独声明。
带代码:
class A implements InterfaceForA
a():void
this.b();
private b():void
console.log('Hello');
Class B extends A
private b():void
console.log('Hi');
在 C++ 中,我将 A 类中的方法 b() 设置为虚拟私有,这样问题就解决了。在 JS 中这根本不是问题。如何在 TypeScript 中做到这一点?
【问题讨论】:
【参考方案1】:在 C++ 中,您实际上会将其设置为受保护。私人成员是私人的。
Typescript >= 1.3 支持受保护的限定符。
见:What is the equivalent of protected in TypeScript?
【讨论】:
在 C++ 中,“私有虚拟”不同于受保护。它可以被覆盖,但不能从派生类中调用。 @AntonPilyak 谢谢!很高兴知道。以上是关于Typescript - 重载私有方法的主要内容,如果未能解决你的问题,请参考以下文章
Typescript Interfaces(接口)添加任意key值/内容