【问题标题】:Typescript - Overloading private methodTypescript - 重载私有方法
【发布时间】: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 中做到这一点?

【问题讨论】:

    标签: typescript private overloading


    【解决方案1】:

    在 C++ 中,您实际上会将其设置为受保护。私人成员是私人的。

    Typescript >= 1.3 支持受保护的限定符。

    见:What is the equivalent of protected in TypeScript?

    【讨论】:

    • 在 C++ 中,“私有虚拟”不同于受保护。它可以被覆盖,但不能从派生类中调用。
    • @AntonPilyak 谢谢!很高兴知道。
    猜你喜欢
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 2018-02-19
    • 2017-11-06
    相关资源
    最近更新 更多