-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extended class cannot read protected parent class field #8512
Comments
As the error message states, there are two constraints on accessing a protected, 1. within a derived class (which is true) and 2. through an instance of the derived class ( The second restriction to ensure that class isolation is not violated. consider this: class Base {
protected state: number | string;
protected doAction() { }
}
class Derived1 extends Base {
constructor(a: Base) {
a.state = "name"; // string is a valid value for Base
a.doAction();
}
}
class Derived2 extends Base {
state: number = 0; // more specific than Base
doAction() {
this.state.toFixed(); // state has to be a number;
}
}
new Derived1(new Derived2()); /// Error!!! TypeError: this.state.toFixed is not a function This a common OO concept and is not specific to TS; you can find more information about this in: |
thanks for detailed explanation |
I just was sent over from #11832. I first thought, that the example presented here by @mhegazy explains, why an access to protected is not possible. However, the example rather shows, that narrowing a type must not be allowed. See the following example:
Command line:
Is there an explanation for this? Actually I never tried that, because I did not expect it to work. But it compiles just fine and crashes at runtime... |
@0815fox aliasing through a base reference when the underlying fields are mutable isn't sound. It's a complexity / soundness tradeoff. The alternative is to make code like this an error, which is cumbersome because it's much more common that fields aren't mutated function process(x: { a: string | number}) {
console.log(x.a);
}
function fn(x: { a: string }) {
process(x);
} |
On my opinion, there should be a difference between the following two function definitions:
The equivalence |
1.8.0-beta
Why this error happen? So
Bar
yet extendsFoo
The text was updated successfully, but these errors were encountered: