-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Strict property initialization (arguably) confused by redefinition of property in subclass #21775
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
Comments
//related #20911 |
I am not sure there is anything we can do here.. the compiler sees a reference to The workaround is to add the definite assignment operator on the declaration, e.g. |
Yeah, this is very similar to #20911, with the difference that we actually are assigning to the property in the subclass constructor, so there's not that complication around whether just defining the field in the subclass would create an undefined own prop.
What do you mean by "what it will be used for"/what's the relevance of that? It seems the compiler should know the type |
Any use of |
Right, I guess I'm saying rule should be that:
So the following would be valid too under my proposal: class Super { /* Same as before */ }
class Sub extends Super {
protected prop: { a: number, b: number };
protected derivedProp: number;
constructor() {
super();
// below would be a totally legal read of this.prop, even though it's not
// used to set the child's this.prop. Uses the parent class's type
// (i.e., so a read of this.prop.b here would be invalid).
this.derivedProp = this.prop.a * Math.random();
// sub class's this.prop still initialized, per the sub class' definition,
// before constructor finishes, so strictPropertyInitialization should be happy.
this.prop = { a: this.prop.a, b: 2 };
}
} |
It would still run into the problem, under a strict implementation of stage-3 props, that your declaration of props causes it to be defined anew with a value of undefined. Try initializing it with |
I was gonna ask about that. I wanna read the spec closer, but I'm pretty sure |
I think the error correctly speaks for itself. |
@RyanCavanaugh Why does
|
TypeScript Version: 2.7.1
Search Terms:
property initialized used sub class
Code
Expected behavior:
The assignment to
this.prop
in the subclasss' constructor should succeed, with the compiler understanding thatthis.prop
, at that stage, has the value + type given to it by the superclass.Actual behavior:
Error:
Property 'prop' is used before being assigned.
The text was updated successfully, but these errors were encountered: