我是 Typescript 的新手,我尝试在这个 playground 中尝试使用 TypeScript .我注意到在 TypeScript 中,基类中的 protected 成员可以被公共(public)成员覆盖:
class Base {
protected name: string = '!'
}
class Derived extends Base{
public name: string = '?'
}
一方面,这对我来说很有意义,因为 Liskov 替换原则仍然成立:基类比派生类有更严格的要求。但另一方面,我注意到私有(private)成员不能被 protected 成员或公共(public)成员覆盖,这对我来说似乎不一致:
class Base {
private name: string = '!'
}
class Derived extends Base{
public name: string = '?' // ERROR!
}
因此我想知道:
我的观察是预期行为还是 Typescript 中的错误?
如果是有意为之,为什么会存在这种不一致?为什么 TypeScript 不要求所有覆盖成员都具有与基类成员相同的可访问性?还是允许所有具有更高可访问性的派生成员覆盖基类中的成员?
最佳答案
这是预期的行为。
您可以将protected
字段设为public
,因为protected
允许派生类读取和写入字段。派生类可以选择使用其读写字段的能力来允许其他人读写该字段。让你写这样的东西是没有意义的:
class Foo {
protected someField;
}
class Bar extends Foo {
public get someFieldButPublic() {
return this.someField;
}
public set someFieldButPublic(value) {
this.someField = value;
}
}
如果您只想公开someField
。
您不能将private
字段设为protected
或public
,因为您没有对该字段的读取或写入权限。它是私有(private)的
;毕竟,如果基类希望您能够访问该字段,他们会使其成为protected
。
关于javascript - 为什么 protected 成员可以被 TypeScript 中的公共(public)成员覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084483/