gpt4 book ai didi

typescript - 为什么不能从子类调用抽象保护方法?

转载 作者:行者123 更新时间:2023-12-04 15:29:54 24 4
gpt4 key购买 nike

这是我在项目中想要的简化版本:

abstract class Parent {
protected abstract method(): any;
}

class Child extends Parent {
protected method(): any {}

protected other() {
let a: Parent = new Child()
a.method()
}
}

class Other extends Parent {
protected method(): any {}
}

尝试调用 a.method() 时失败。错误内容如下:

Property 'method' is protected and only accessible through an instance of class 'Child'.

Playground Link

据我所知,问题出在 a.method() 不是从实际实例 a 中调用的事实。但是,它仍然是从 Child 实例中调用的,所以错误看起来很奇怪。同一个基类的实例不是彼此“ friend ”吗?

最后,如何在不失去 protected 带来的好处的情况下解决我的问题?谢谢。

最佳答案

根据 TypeScript 规范,如果基类变量受到保护,我们不能直接在非 this 对象上从派生类使用它。因此,您可以调用 this.method(),但不能调用 a.method()

TS 规范第 120 页倒数第二段:https://github.com/microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.pdf

关于typescript - 为什么不能从子类调用抽象保护方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61429836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com