-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Class Constructors (for abbreviated Knockout model-style typescript adaptations) #479
Comments
This is roughly some sort of 'primary constructor' syntax with initialization (ex http://stackoverflow.com/questions/22908005/primary-constructors-in-c-sharp-vnext). While certainly a nice feature in general I don't think this adds enough value for the risk it presents at the moment. It's entirely possible that a future version of EcmaScript adds some similar but different pattern for primary constructor type behavior which would present real issues for TypeScript compatibility. In the end the TypeScript syntax here is no more verbose than what a great many other languages use for this kind of pattern. Note from the ES6 class proposal:
|
Then can TypeScript have a way of adding fields from within the constructor, without having to declare their type explicitly outside the constructor or in an interface? |
You can write something like this: class Foo {
constructor(node: string); // Public signature
constructor(node: string, // Implementation signature with parameter properties
public myObservable = ko.observable(node),
public thing = node.length,
private otherThing = 0) {
// Additional ctor logic here
}
} |
OMG! That is so baller Thanks! |
So here's an updated example of what you can do with that.
|
Is it a bug that |
That's not an error because |
Yes, I understand that |
The typechecker only works "bottom-up". I agree that we could in principle detect this, e.g. var x: string;
var y: any;
var z: number = y || x; // Shouldn't be allowed, in theory But we'd either need to not collapse union types with |
Well, thanks. I'll leave that to you to know whether that issue already exists under different wording or how to explain the essence of it in a new issue. |
Knockout models, which are very concise in javascript, are obnoxious to define in typescript (one of the few things that gets longer in typescript). I'm suggesting the following syntax to make it much cleaner. (Perhaps this is a duplicate?)
This syntax adds a constructor signature with parameters which can be referenced in the field initializers. This is to replace javascript's easy
this.someNewProperty = '...'
legitimacy while retaining the strong typing information of typescript (that is, not resorting to a cast asany
, etc)The generated model seems pretty much what you'd write by hand:
The alternative (current way) is that all the fields have to be declared and separately assigned in a constructor:
The text was updated successfully, but these errors were encountered: