Repository navigation
Suggestion: Allow declaring class members within a constructor #766
Description
Activity
👍 Also provides an easy syntax to put members directly on
thisinstead ofprototypeRyanCavanaugh commented
on Sep 29, 2014 MemberMore actionsI would note that you can use parameter property syntax to get something very close to this already:
class Foo { // Actual overloads constructor(n: string); // Constructor impl + member fields constructor(n: string, public bar = 'thing', public baz = 200, private qua = [] ) { // constructor body } }
RyanCavanaugh commented
on Sep 29, 2014 MemberMore actionsYou can reference it by name
class Foo { // Actual overloads constructor(n: string); // Constructor impl + member fields constructor(n: string, public bar = 'thing' + n ) { // constructor body } }
Well, you learn something new every day. Thanks Ryan!
This code does work in TypeScript 1.0.
class RightTriangle4 { constructor(height: number, width: number) constructor(_height: number, _width: number, public height = ko.observable(_height), public width = ko.observable(_width), public hypotenuse = ko.computed(() => { console.log("hypotenuse 4 calculated"); return Math.sqrt(height() * height() + width() * width()); }) ) {} } var rt4 = new RightTriangle4(12, 16); console.log("hypotenuse 4: " + rt4.hypotenuse()); // 20
I am not sure that this syntax looks as nice as the suggestion, and something just screams "wrong!" about doing actual work inside a method signature, in particular arguments referencing each other, but this certainly works in TypeScript 1.0.
Ryan Cavanaugh (@RyanCavanaugh) Thanks so much for the suggestion. After working with this a bit, I intend to revise the original post considering this as a third form that works, but is problematic. In this case, the main issue is that function arguments referencing each other and executing code inside a method signature toes the line of violating the "principle of least astonishment".
I know that this is not a priority for the team at this time, but would you consider a pull request for the original suggestion?
I see where you're coming from but ultimately this is adding complexity and syntax for a pattern that people are generally ok with in a variety of languages. With the 3rd proposal the compiler and users have to walk the constructor body to try to understand the public surface area of a type (trading brevity for clarity in some cases) and there needs to be some interaction with the existing parameter properties among other things. We just have a limited budget for syntax and other changes and the value here just isn't that high.
- addedSuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it addsDeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript vision
on Oct 8, 2014 Dan Quirk (@danquirk) Thanks for the consideration.
DanielRosenwasser commented
on Apr 4, 2015 MemberMore actionsDan Quirk (@danquirk), were you leaning towards reopening this issue?
Daniel Rosenwasser (@DanielRosenwasser) not really. This doesn't solve the problem of 'my ES6 code is an error in TypeScript'. It still requires new syntax at which point I don't think it's adding enough value over the current syntax options once you've decided it's worth the effort to augment your code to satisfy a TypeScript rule. If we were actually solving the ES6 problem that'd be interesting (ex inferring from this.foo assignments in the constructor to implicitly infer the shape of your type) or else people might just lean towards the future ES class syntax like we propose now https://gist.github.com/jeffmo/054df782c05639da2adb
Reacted by Ignat IgnatovI still appreciate the consideration, Dan. I'm definitely interested to hear how the constructor signature short-hand snuck into the language if this isn't adding enough value for you. Do you regret adding that?
PS: This is not intended to be snarky just curious.
RyanCavanaugh commented
on Apr 6, 2015 MemberMore actionsFWIW class parameter properties have existed in TypeScript basically forever (i.e. before I joined the team which was well before we went public).
Given the historical context of how much the ES6 class design was moving around, I think it was the right decision. The proposed syntax is very similar (identical?) to the 'harmony' class proposal that was popular at the time (http://wiki.ecmascript.org/doku.php?id=harmony:classes#proposal_history). Had TypeScript implemented some sort of constructor-body semantics and then had ES6 land on the harmony proposal with slightly different semantics, that would have been a disaster. Constraining those keywords to parameter positions was a good trade-off for avoiding conflicting with a future ES6 standard while still adding a ton of convenience to the language.
6 remaining items
aluanhaddad commented
on Apr 1, 2017 ContributorMore actionsI still feel that taking maximum advantage of type inference is the correct way to use TypeScript.
I strongly agree with this.
Every day I see code likeclass MyComponent { names: Array<string> = ['hello', 'world']; // redundant }
or worse
class MyComponent { names: any = ['hello', 'world']; // depressing. }
It is amazing how the poorly coded official tutorials of one popular framework can have such a negative impact on the use of a language.
However, looking over your original proposal, and I might be missing something here, it seems that there would be no new syntax required to implement it. It would simply imply tracking assignments to
thisaltering the shape of the class along the way.What I mean is that this
class RightTriangle3 { constructor(height: number, width: number) { public this.height = ko.observable(height); public this.width = ko.observable(width); public this.hypotenuse = ko.computed(() => { console.log("hypotenuse 3 calculated"); return Math.sqrt(this.height() * this.height() + this.width() * this.width()); }); } } var rt3 = new RightTriangle3(9, 12); console.log("hypotenuse 3: " + rt3.hypotenuse()); // 15
could just as well be this
class RightTriangle3 { constructor(height: number, width: number) { this.height = ko.observable(height); this.width = ko.observable(width); this.hypotenuse = ko.computed(() => { console.log("hypotenuse 3 calculated"); return Math.sqrt(this.height() * this.height() + this.width() * this.width()); }); } } var rt3 = new RightTriangle3(9, 12); console.log("hypotenuse 3: " + rt3.hypotenuse()); // 15
The effect on the JS code would be identical, in fact that is a valid JavaScript constructor body.
The Salsa language service exhibits this behavior.
I get why they don't allow that by default. Allowing implicit declarations - even just in constructors - opens the door to classes of bugs that TypeScript is intended to prevent. This proposed syntax was a way to make such declarations explicit. Perhaps an --allowImplicitMemberDeclarations switch (to mimic Salsa) is a better solution, however that would continue to add to the present constellation of switches, which is another day 1 problem (can't blame TS team for this one, though).
aluanhaddad commented
on Apr 1, 2017 ContributorMore actionsI understand the desire to be explicit but wanted to point out that it doesn't require new syntax. New syntax in value position is a showstopper.
fair enough.
- addedIn DiscussionNot yet reached consensusNot yet reached consensusand removedDeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds
on Apr 3, 2017 RyanCavanaugh commented
on Apr 3, 2017 MemberMore actionsI think this deserves another go-around. We infer from
thisassignments in JS and considered doing this for TS classes with zero local property declarations. But without a global quickfix, I think we're potentially making class-based ES6 -> TS migration too difficult (ironically)Reacted by Steve Ognibene and Misha Kaletsky- addedToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it addsand removedIn DiscussionNot yet reached consensusNot yet reached consensus
on Apr 24, 2017 RyanCavanaugh commented
on Apr 24, 2017 MemberMore actionsThought about it again but outcome is basically the same ( #766 (comment) ).
Particularly, ES-Next public field initializers are coming down the pipe, so constructor-initialized properties should be getting less common at some point in the future.
Thank you for reconsidering it.
- locked and limited conversation to collaborators
on Jun 18, 2018
Problem Statement: In TypeScript 1.1, there are two basic ways to initialize complex properties with strong typing via a parameterized class constructor. Both have disadvantages. I will illustrate this with a simple example that uses Knockout, but this issue applies to any other JavaScript library that implements complex objects via initializer functions.
"Method 1" is to instantiate the properties outside of the constructor using a throw-away value, and then to set the desired value inside the constructor (see
RightTriangle1below). This method has the advantage of being rather simple to program/maintain because TypeScript automatically infers the property's type. However, this has the potential to cause ripple effects or performance issues at runtime because the code to instantiate each property is run at least twice.Knockout happens to have an advanced feature to defer execution of a computed, but that's beside the point. Other libraries may not support such a feature and it's just one more thing for the developer to keep track of.
"Method 2" is to declare the properties with an explicit type outside of the constructor, and then to instantiate them inside the constructor (see
RightTriangle2below). This method has the advantage of eliminating the runtime double-instantiation issue, but it also eliminates the convenience of having TypeScript infer the types.Method 2 has the drawback of extra work if a type is ever changed, but much worse than that, it places the burden on the developer to figure out what the type of each member should be. For trivial members (string, number, etc.) or libraries you've written yourself, this is merely busy-work, however for complex types used by a JavaScript library it is sometimes difficult to determine unless the developer is quite familiar with the library's definition. Lastly, this is just the sort of syntax that would make a JavaScript developer who was new to TypeScript think, "This is exactly what I was afraid of! Look at all that extra code I'm forced to write that just gets thrown away in the end!"
In summary of the problem, "Method 1" begs performance or logic problems, and "Method 2" is too wordy.
Proposal: "Method 3" Fairly early on in the public life of TypeScript, the team added the ability to indicate retained fields by placing visibility modifiers on constructor parameters. This feature is awesome, but it only helps with trivial properties. I would like to propose adding a new feature to TypeScript to allow this idiom within the body of a constructor as well. This would permit compiling the code in the
RightTriangle3example below. Note the public modifiers on height, width, and hypotenuse.With this proposal:
RightTriangle3class would have the identical JavaScript emit asRightTriangle2.RightTriangle3TypeScript compile-time type interface would also be identical toRightTriangle2.RightTriangle3is the most succinct of the three.RightTriangle1is 12 lines long (besides being "wrong"),RightTriangle2is 13,RightTriangle3is just 10. Additional observable or computed properties inRightTriangle1andRightTriangle2add two lines of code each; withRightTriangle3only one line of code is added each.RightTriangle3is still very close to the emitted JavaScript (and therefore unlikely to create future incompatibility issues).RightTriangle3enables a simple cut+paste migration path to implement a constructor (the developer would just have to paste in "this." on each line). With TypeScript 1.0, implementing a constructor is a lot more work. For example if convertingRightTriangle1toRightTriangle2, the developer must determine and explicitly type out each member declaration with its type before migrating the instantiation code.Specifics:
Inside a class constructor function only, a visibility modifier (
public,private, orprotected) may modify a property on the instance variablethis. If so, the statement is considered a declaration of that property on the class and the type is inferred according to the normal TypeScript rules. The following example classAis legal under this proposal:The above code is identical to this TypeScript 1.1 code:
Use of a visibility modifier is otherwise not permitted within the body of a constructor. For example, class
Bbelow would be a syntax error becauseproperty1is not qualified as a property ofthis. This condition should cause a new emit-preventing type error along the lines ofVisibility modifiers within a constructor may only modify properties of "this".Use of a visibility modifier is similarly not permitted within a normal function member. For example, class
Cbelow would be a syntax error, because in this proposal class properties can only be declared in this manner within the constructor. This condition should cause a new emit-preventing type error along the lines ofVisibility modifier declarations are only legal within the parameter list and body of a class constructor.Use of the
staticmodifier is similarly not permitted within a normal function member or the constructor. For example, classDbelow would be a syntax error because under this proposal,staticclass properties can only be declared using the existing TypeScript 1.0 syntax (within the body of the class). This condition should cause a new emit-preventing type error along the lines ofShorthand visibility declarations may not be used on static properties.What happens if a declaration occurs inside of a branch?
For the purpose of the TypeScript type system, any branching, looping, etc. inside the constructor should be ignored. Furthermore, the JavaScript should be emitted exactly as if the public, private, or protected modifier were not present. Under this proposal, TypeScript should consider class
Ebelow to be valid. At compile time, TypeScript will consider classEto have a property calleddescriptionof typestring(even though at runtime the initialization code would never execute).What happens if there is a duplicate declaration and the types match?
This should not prevent the emit. The second and successive duplicates should raise
error TS2300: Duplicate identifier 'PROPERTY_NAME_HERE'.just like how existing duplicate declarations work.What happens if there is a duplicate, but one is a subtype of the other, or even if the types do not match?
The same type resolution logic should be applied if the duplicates occurred as simple type declarations in the class body (outside the constructor). The second and successive duplicates should raise
error TS2300: Duplicate identifier 'PROPERTY_NAME_HERE'.. This should not prevent the emit. This may incidentally result in downstreamerror TS2339: Property 'PROPERTY_NAME_HERE' does not exist on type 'THE_PROPERTY_TYPE'.wherever sub-properties of the property are used (just like in TypeScript 1.0).In all other scenarios (such as with inheritance chains, subtypes, supertypes, assignability relationships, and generics), the same behavior as a class written like
RightTriangle2in TypeScript 1.0 should be used when evaluating what should happen with a class written likeRightTriangle3using the new shorthand syntax.I believe that this syntax fits in nicely with both the goals and non-goals of TypeScript and I hope that you'll consider it or something similar. Thanks for reading this.