为什么在TypeScript中公共成员可以覆盖受保护的成员? [英] Why protected members can be overridden by public members in TypeScript?

查看:124
本文介绍了为什么在TypeScript中公共成员可以覆盖受保护的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Typescript的新手,我尝试在这个游乐场.我注意到在TypeScript中,公共成员可以覆盖基类中受保护的成员:

I am new to Typescript, and I tried to played around a little with TypeScript in this playground. I noticed that in TypeScript, a protected member in base class can be overridden by public members:

class Base {
    protected name: string = '!'
}

class Derived extends Base{
    public name: string = '?'
}

一方面,这对我来说很有意义,因为李斯科夫替代原则仍然成立:基类比派生类有更严格的要求.但是另一方面,我注意到私有成员不能被受保护的成员或公共成员所覆盖,这对我而言似乎是不一致的:

On the one hand, this makes sense to me since the Liskov Substitution Principle still holds: base class has stricter requirements than derived class. But on the other hand, I noticed that private member cannot be overridden by protected or public one, which seems inconsistent to me:

class Base {
    private name: string = '!'
}

class Derived extends Base{
    public name: string = '?'  // ERROR!
}

因此,我想知道:

  1. 我的观察结果是预期的行为还是Typescript中的错误?

  1. Is my observation an intended behavior or a bug in Typescript?

如果有意,为什么存在这种不一致?为什么TypeScript不要求所有重写成员具有与基类中的成员相同的可访问性?还是允许所有具有较高可访问性的派生成员覆盖基类中的成员?

If it's intended, why this inconsistency exists? Why not TypeScript requires all overriding members having the same accessibility as members in base class? Or allowing all derived members with higher accessibility overriding members in base class?

推荐答案

这是预期的行为.

您可以将protected字段设置为public,因为protected允许派生类读取和写入字段.派生类可以选择使用其读取和写入字段的能力,以允许其他人读取和写入字段.没必要让你写这样的东西:

You can make a protected field public because protected allows a derived class to read and write a field. The derived class can choose to use its ability to read and write the field to allow others to read and write the field. There's no point making you write something like this:

class Foo {
  protected someField;
}

class Bar extends Foo {
  public get someFieldButPublic() {
    return this.someField;
  }
  public set someFieldButPublic(value) {
    this.someField = value;
  }
}

如果您只想公开someField.

您不能将private字段设置为protectedpublic,因为您没有对该字段的读写权限. private;如果基类希望您可以访问该字段,那么毕竟他们会将其设置为protected.

You can't make a private field protected or public because you don't have read or write access to that field. It's private; if the base class wanted you to have access to the field, they would have made it protected, after all.

这篇关于为什么在TypeScript中公共成员可以覆盖受保护的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆