-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
Wrong field value in inherited constructor's submethod and after #9455
Comments
Please see my comment in #9060 (comment) |
I agree that calling virtual methods from constructor of a base class is risky because specific order of calling constructors chain - but here I have an issue with field initializers. C# treats them well:
C# code from above gives expected output: foobar. TypeScript treats field initializers differently - in generated JS code it just puts them to the constructor, between super() call and rest of constructor's code:
Is that a problem just to reverse order in generated construtor - put field initializers before super() call? That resolves the problem I have and adds consistency with C# behavior to the language. |
Putting field initializers before the super call is even worse because base class field initialization occurs during the class Base {
myName = 'the default name';
}
class Derived extends Base {
myName = 'derived name';
}
var x = new Derived();
console.log(x.myName); // should not print "the default name" ! |
See also #1617 |
Also agree, wrong idea. What about this one?
I've moved field initializers from constructor to the dedicated virtual method. It works well in my scenario, does not break yours and also fixes #1617. |
Breaking change concerns aside, in general we don't know whether a given base class is a TypeScript-generated class or not, so we wouldn't know whether to put initializers in |
I should also add that the current initialization order is very likely to be the spec'd behavior of ES7+ class property initializers. |
Well, with non-TS base classes it is indeed a problem - I haven't taken that into consideration. What do you think about compiler warning on reading fields in constructor and constructor's submethods? That would save much of a developer time in all mentioned scenarios, I think. |
Literally you'd want a warning for this code? class A {
size = 10;
constructor() {
console.log('size = ' + this.size);
}
} |
Yeah. This initialization order is specific to TypeScript, so warning would help beginers like me to get the very idea, without hitting the wall, searching forums, even starting discussions like this one. |
TypeScript Version: 1.8.10
Code
Expected behavior:
Console prints out:
Actual behavior:
Console prints out:
The text was updated successfully, but these errors were encountered: