Partial classes
Add support of partial classes. Mixins is not the same, because it's run-time realization. Need compile realization, where partial classes will be combine into one before converting typescript to javascript.
//FileA.ts
partial class ClassA
{
constructor(public name: string) {}
public sayHello(): string { return "hi!"; }
}
//FileB.ts
partial class ClassA
{
public sayBye(): string { return "by!"; }
}
will be:
partial class ClassA
{
constructor(public name: string) {}
public sayHello(): string { return "hi!"; }
public sayBye(): string { return "by!"; }
}
Just to make sure, you do realize that partial functions have a very specific meaning and what you're describing are not partial functions by any stretch of the imagination? Code generation is useful, I use it as well.
@aluanhaddad . Do you understand the term "one compilation unit in several files" ? Javascript of course is not compilation language but a) function should be fully parsed before execution and we can name this "compilation" b) Typescript is compilation language.
To help your imagination:
function partial func(arguments) {
return function() {
return codegenerated(arguments);
};
}
function partial func(arguments) {
function codegenerated(arguments){
// ...
}
}
I also do not use partial classes often: to use them effectively we need to store codegeneration parameters in "manual" part and to read this configuration we should have good language parser (not reflection). But that how it is: partial classes is only one instrument from many to make codegeneration comfortable.
@rpokrovskij I apologize if I came off as antagonistic. I meant no offense or disrespect.
Your example has aspects which would require a fairly formal description in their own right. This proposal was not originally about directly enabling code generation scenarios.
@aluanhaddad.... "Simply avoid classes and your problem will be solved" - seriously, that is a solution to a problem?! Probably if I avoid using JavaScript - I can solve the problem of this whole discussion. Also a solution, isn't it? Unfortunatelly we have this shitty language in our universe because it was lucky enough to get into web many years ago. Anyway, this is an offtopic.
"break almost every tool known to man" - how is that possible??? How?!?! I try to imagine breaking something by using partial classes in TypeScript, but I cannot. I simply cannot. Please, help me here with some real life example.
Now imagine you have built a car to transport boxes. It works without any problems. You hire a worker, who loads up the car. The worker takes two boxes at a time and puts into the car. Still everything works fine. One day the worker leaves for another company and you hire a new one. The new one takes a single box, loads it, takes another single box and loads it too. Logically: everything is ok. But you run around and scream: stop, stop, we have a system failure! :)
"Simply avoid classes and your problem will be solved" - seriously, that is a solution to a problem?! Probably if I avoid using JavaScript - I can solve the problem of this whole discussion. Also a solution, isn't it? Unfortunatelly we have this shitty language in our universe because it was lucky enough to get into web many years ago. Anyway, this is an offtopic.
ES2015 has many things wrong with it for sure. ES5.1 had many things wrong with it for sure. In my opinion, a lack of classes was not one of those things. My point is that by using techniques like the revealing module pattern you obviate the need for partial classes. TypeScript provides sugar for the revealing module pattern, namespaces.
"break almost every tool known to man" - how is that possible??? How?!?! I try to imagine breaking something by using partial classes in TypeScript, but I cannot. I simply cannot. Please, help me here with some real life example.
If you use ES Modules, this is problematic. Any tool that relies on the physical artifacts of the compiler having a correspondence with their uncompiled counterparts would be subject to this. That said, TypeScript could adjust for this in the emit, a massive change, but it would then be emitting JavaScript that did not match the TypeScript that you wrote.
So, basically, the evolution of a language is being hold back by the tools, which will never evolve without the evolution of the language. Sorry, but I see here only the search for the reason not to evolve.
What are the benefits that partial classes give, that you can't already do with the language in a different way? It's nice syntactic sugar, sure, but what the true gains? Is there a concrete example other than to make it more like C#?
Aside: For the record I started as a C# Developer, moved to JavaScript / C# from there. Once TypeScript 0.8 was announced I was sold, not because it was C# for JavaScript, but because it was taking strict JavaScript and making it better for developers that enjoy the strong types of C#.
TypeScript is not C#, and should not strictly inherit features from C# just because C# has them. Just as C# should not inherit features from TypeScript. I can't count the times I've wanted features like union types in C# because they're so awesome for TypeScript, but they are not right for the language yet.
So far I've read Code Generation and Code Organization.
Code Generation, look at Module Augmentation there are some deficiencies I called out here but I'm sure they can be fixed.
Code Organization, I guess use regions (lol)? There are many other ways to organize you code, if you have one God class (for whatever reason) you can always split it up into many God classes. At the surface the god class is the import everyone sees and uses, under the covers however it's made of many classes perhaps as properties of the god class. If you are using partial classes for organization I would argue you need to refactor your code a little bit to try and SOLIDify your code.
I've been able to fit augmentation into most code generation scenarios I've encountered to date.
For Omnisharp-Client I use the interface extension here where OmniSharp.Api.V2 is a generated via reflection in C#. At the bottom of the file I have a tool that stubs out all the methods for that interface.
For RxJS we use to to map all of our methods that are on Observable.
I just can't reason around some of the issues with partial classes. For example if we are given 3 partial classes.
MyAwesomeClass1.tsMyAwesomeClass2.tsMyAwesomeClass3.ts
Scope: Global Module (using namespace / module)
Global compilation is where this appears to be the easiest. As TypeScript already merges namespaces together.
If my tsconfig.json only contains the file paths for Class1 and Class2 then anything that is in Class3 is not automatically merged in.
- At first this seems like user error, but it won't immediately be apparent why the methods from Class3 are not included. This is a huge usability problem that will lead to confusion.
Scope: External Modules (import / export)
With external compilation, each file is really considered module (or hell Assembly in the .NET world) because each module has an explicit list of all it's dependencies (imports) and all of it's public api (exports).
How do you reason about these scenarios?
Given only one file reference, what is the behavior of the class? Does it automatically merge Class2 and Class3?
- Does the default definition of Class1, Class2 and Class3 all export the exact same value?
- What file is emitted to disk?
- What will the underlying JavaScript look like for all supported formats (amd, umd, commonjs, etc)
// somefile.ts
import { MyAwesomeClass } from 'MyAwesomeClass1';
new mac = new MyAwesomeClass();
mac. // What methods are available here?
Do we have to explicitly import all instances of the class? (If we do that defeats the purpose imo). What happens when you import everything in one file, but not another, to the methods cary over? This could lead to really strange errors given a complex dependency graph where the class is used once, without the extra partials. Would the values be augmented? or would the methods magically not work until the other file is loaded that brings them in?
// somefile.ts
import { MyAwesomeClass } from 'MyAwesomeClass1';
import { MyAwesomeClass } from 'MyAwesomeClass2'; // or maybe import 'MyAwesomeClass2';
import { MyAwesomeClass } from 'MyAwesomeClass3'; // or maybe import 'MyAwesomeClass3';
new mac = new MyAwesomeClass();
mac. // What methods are available here?
@david-driscoll Just my two cents here:
It's nice syntactic sugar, sure, but what the true gains?
Isn't nice syntactic sugar the whole point of any language? From an operative point of view, all we need is loops, if-clauses and iteration to do everything. The rest is just nice syntactic sugar in order to be more productive and provide other similar non-functional qualities.
And while languages are generally good at the operational part of instructing a computer, they generally suck in the organizational part of writing code. We have these cultural ad-hoc artefacts like objects, classes, inheritance and such, but no solid theoretical foundation, afaik, that really explains the domain of organizing operations and all the abstractions we are trying to construct and represent in our source code in order to be able to work with it in a good way.
There is two things I love about TypeScript: 1. It lets us use typed javascript so that it's suddenly manageable to build complex systems in the client. 2. The type system is extremely expressive (because it was forced to be able to express all kinds of patterns in javascript that people could write without the limitation of a type system).
But in regards of structuring code, I don't think it's very significantly less sucky than any other language. And I wish we could be more innovative here. Give users more freedom to experiment with the organizational part of the language. Opening up to and striving for new structural expressiveness instead of being restrictive and suspicious.
Partial classes are not only very convenient for code generation specifically, but it increases the freedom in organization in general. Freedom which we need in order to get out of this tar-pit of code organization.
@david-driscoll what is the point of having partials? Well, once again: code generation. What is wrong with your proposed solution? It is a workaround. Yet another workaround (and pretty dirty workaround). We already have a shitty language (javascrtipt), which is filled with workarounds. Instead of thinking about their main tasks, javascript devs spend a lot of time thinking about the workarounds. With your proposed philosophy we can throw away the whole TypeScript language. Because (surprise, surpsise) the whole types system can be simulated in pure javascript - by using workarounds. Why care about a more expressive language (like Typescript) if you can simulate anything with workarounds? Why write a single line of code when same thing may be written in twenty lines? Bring back the salaries based on a number of lines of code written! Short, expressive code is for pussies, isn't it?
And no: request to have partials in TypeScript is not based on idea that C# has them. I don't believe TypeScript should have something just for the sake of having it because another language has it.
And finally: why do you think that if you do not use something - nobody needs it?
@greendimka I wasn't trying to spark any hostility :shield:. I am simply trying to understand the scenarios or if there are ones I'm unaware of which frankly is entirely possible!
Now keep in mind, I'm not on the TypeScript Team, I'm just an advocate, but the team has been pretty silent here. The team may very well chime in when they have something specific to say, and I will defer to them if they choose to do so.
One of the key tenants that the TypeScript team has held to is try and keep TypeScript moving in sync with the direction of ECMAScript, and to avoid making any specific features that may cause them to diverge from the overall direction JavaScript is evolving to.
It's not that I wouldn't use it (I probably would if it existed). Problem is as it stands in this issue partial classes have may caveats so it seems doubtful it will be implemented any time soon. It will probably stay this way for a while until a) it becomes a must have feature for a high value stakeholder or b) a proposal steams into the later stages of TC39.
I don't see Module Augmentation as a work around. It allows you to augment the type system, and allows for many of the Code Generation scenarios that have been detailed in this thread. This is a stepping toward other language features.
-
Is it ugly? Absolutely, ugly as all hell. That said if you are generating the code, what is the difference? Only your generation tool needs to be worried about how to augment the class. Once you have run your code generation tool, and include your modules, you get full intellisense and compilation errors, etc.
-
Is it perfect? Far from it! I see a far more common scenario with mixins needing to be supported at the language level. And I think something line with decorators as proposed here makes sense, though again there isn't any specific proposal.
@david-driscoll, sorry for being extremely rude. I really tend to stand on a side of positive progress.
I would like this so I could put static implementations in a partial class.
Since it doesn't look like this will come to fruition soon, I would like to propose a workaround that we found. There are some comments like this, but I didn't see one with these specifics reading.
We would like Partials for use in a code generation scenario where we want to be able to extend our generated TypeScript code. However, we are generating models that have interdependencies so inheriting from our classes doesn't work well in the traditional sense. The generated classes that reference other classes don't end up with the right type of object being referenced and we would end up with a complex factory pattern to get the correct instance types created.
We ended up changing our generated classes to base classes, but only in the class declaration. We then created stub classes that inherited from our new base classes. We could then extend these new classes and they would inherit all their content from the base class.
For example: If we generated a class Person, we would now generate a PersonBase. All the generated code goes in this class. We would also generate an empty class Person that extends PersonBase. This class would only ever get generated once. We then put all our generated code in PersonBase, and all the custom code manually goes into Person. All generated references to Person remain as Person and not PersonBase. This way all IntelliSense continues to work.
File 1: Base Class
module ViewModels {
export class PersonBase {
// Generated members
public anotherPerson: Person;
constructor(){
// Generated constructor code
}
}
}
File 2: Actual Class
module ViewModels {
export class Person extends PersonBase {
// Custom methods
public NewVariable: string = "NewVar";
constructor() {
super();
// Custom constructor code
}
}
}
This has solved our partial class problem with generated code. Kudos to Andrew Scott for coming up with the idea.
I'd really like this too, since I'm generating some code with a code generator, and I need to add some changes to it. Partial classes will allow regenerating the code without having to add the changes again later (which might be big or complex)
There's an important reason to have partial classes which I don't think has been mentioned yet: gradually migrating JS to TS. In Javascript, particularly pre-ES6, classes can look like a bunch of:
Foo.prototype.someFunction = function() {/*....*/}
And these can be spread over multiple files without any special handling. Converting a codebase like that into modern TypeScript currently requires moving functions so that all the members of a class are in the same file, which can be a pretty invasive change. With partial classes, the migration could be done using only local edits.
@RyanCavanaugh You mention that everything asked for here can be syntactically handled with other TypeScript syntax:
I think the mixin proposal has a lot more open questions. The partial class proposal here is just a codification of things that are already allowed in TypeScript, just with some syntactic sugar (this feature could literally be done as a syntactic remapping to things we already have).
So how would one go about doing this in TypeScript?: File1.ts:
// Imagine this file is code generated and could be regenerated during development
export partial class Contact
{
firstName: string;
lastName: string;
partial OnInit( args: any ) : void;
constuctor( args: any )
{
this.OnInit( args );
}
}
export class Address
{
addr: string;
city: string;
state: string;
zip: string;
}
File2.ts
// See where I'm going with this? This file would be hand edited and allows me to specify associations and children.
partial class Contact
{
Addresses: string[] = [];
partial OnInit( args: any ) void
{
this.firstName = args.firstName;
this.lastName = args.lastName;
this.Addresses.push( new Address() );
}
}
Transpiling the above would emit one JS class for Contact, something like this:
var Contact = (function () {
function Contact() {
this.Addresses = [];
}
Contact.prototype.constuctor = function (args) {
this.OnInit( args );
};
Contact.prototype.OnInit = function (args) {
this.firstName = args.firstName;
this.lastName = args.lastName;
this.Addresses.push(new Address());
};
return Contact;
})();
var Address = (function () {
function Address() {
}
return Address;
})();
Note that in the end I want one class named Contact and I don't want to have to subclass two separate classes into a third.
@cosmoKenney
Here's an example of something that will work. It's not as syntactically surgared as partial is however it works and is a very functional solution.
// address.ts
export class Address
{
addr: string;
city: string;
state: string;
zip: string;
}
// contact.impl.ts
import { Address } from './address';
// Class implementation, do the things here that are not code generated
export class Contact {
firstName: string;
lastName: string;
addresses: Address[];
constructor(args: any) {
this.onInit(args);
}
}
// extending the interface here
// define methods you know will need in the constructor only
// This only applies to the constructor however
export interface Contact {
onInit(args: any): void;
}
// contact.partial.ts
import { Contact } from './contact.impl';
// Implement the extended contract here
Contact.prototype.onInit = function(this: Contact, args: any) {
this.addresses = args.addresses.concat();
// do stuff;
};
// Adding another method (not part of the extended interface)
Contact.prototype.somethingAwesome = function(this: Contact) {
// do awesome stuff here
};
// Tell TypeScript "I added this here!!!!"
declare module './contact.impl' {
interface Contact {
somethingAwesome();
}
}
// contact.ts
import { Contact } from './contact.impl';
import './contact.partial';
// Bring it all together (perhaps there are more than one partial class?)
export { Contact };
// main.ts
import { Contact } from './contact';
// use the contact!
const contact = new Contact(['my', 'args']);
const {firstName, lastName} = contact;
contact.somethingAwesome();
Alternatively you could also code generate the interface and use the interface extension implement that.
There may also be ways to use the new Mixin functionality, however I have not dived into that yet myself enough to give a qualified answer.
@david-driscoll Wow. My head just exploded.
I wonder if community will end up with a fork, which simply supports partial classes without blowing out a problem out of it. So far have not heard any real arguments against partial classes. Only few reasons to justify a laziness.