TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Partial classes

Open disshishkov opened this issue 12 years ago • 224 comments

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!"; }
}

disshishkov avatar Aug 29 '14 08:08 disshishkov

True that :/

tsvetomir avatar Sep 14 '16 15:09 tsvetomir

For large systems with code generated classes, i.e. Entities, service layer clients etc, partial classes as per the C# design, provide a very elegant solution when generated code needs to be extended with additional state and behavior. On my present project, where we have ~500 code gen classes, I miss this feature dearly.

dcworldwide avatar Sep 21 '16 07:09 dcworldwide

I still don't understand why some people are so hostile against a feature that has been proven useful elsewhere, except saying "it is a bad idea".

yahiko00 avatar Sep 21 '16 09:09 yahiko00

It seems this hasn't been discussed much on esdiscuss, the only thread I found has 9 posts.

saschanaz avatar Sep 21 '16 09:09 saschanaz

@yahiko00 It is not that I am hostile to the concept. As you say it is very useful in languages such as C#.

As an enthusiastic C# programmer, I find partial classes to be very helpful for certain tasks. However, they do not interfere with the other aspects of the language. They do not break key related abstractions such as namespaces, assemblies, and arbitrarily orderable type declarations.

JavaScript, on the other hand, has a module system that is nascent at best. Classes are a new and, I would argue, as yet not very expressive feature of the language, they need time to grow.

If we take a step back for a moment and consider extension methods, another powerful, and far more useful feature of C#, I would love to see them added to JavaScript but there are fundamental problems with doing so that have yet to be resolved.

When we reach a point where partial classes can be specified without breaking or severely constraining far more fundamental concepts such as modules, I will be all in favor of adding them.

That said, as @SaschaNaz points out, this does need to be addressed in ECMAScript.

aluanhaddad avatar Sep 21 '16 12:09 aluanhaddad

Maybe anyone interested can open a new thread on http://esdiscuss.org and post the URL here so that we can continue discussion there 😄

PS: Or on more-GitHub-like ES Discourse. PS2: Or on also-GitHub-like-and-more-active WICG.

saschanaz avatar Sep 21 '16 12:09 saschanaz

I too would love to see some construct that allows for code generation for TS. Partial classes work great for this in C#.

Maybe I am missing something, but it seems to me that the core issue is extending a class with access to 'private' variables from somewhere other than in the constructor, preferably from another file.

GrantErickson avatar Sep 23 '16 04:09 GrantErickson

Based on the discussion it seems like much of the 'safe' TS innovation has been done. Now we are just waiting to see what the ES governance body does because we don't want to break anything going forward. Totally valid, but a little disheartening because I was hoping for a faster moving train with TS.

GrantErickson avatar Sep 23 '16 04:09 GrantErickson

A prerequisite is finding a good desugaring:

Although I previously thought partial classes were pretty silly because you could just add to the class directly, I can see the appeal given that doing so will involve making your methods non-enumerable plus fixing the super binding (the latter of which is currently impossible in ES6).

We first need to figure out a good desguaring for classes in general into compositional, imperative primitives, like the old toMethod. But once we have that, adding some more sugar on top like partial classes might be reasonable, depending on how ergonomic---or not---those primitives end up being.

Not sure what this exactly means but probably like this:

class A {
  foo() { return "foo" }
}
class B extends A {
}

partial(B, class {
  get foo() {
    return super.foo(); // should work
  }
});

saschanaz avatar Sep 23 '16 04:09 saschanaz

(Cross posted on esdiscuss)

It seems there is a fairly simple way to implement partial class in pure JS (with ES2017 getOwnPropertyDescriptors). ES people may think a syntax sugar will even not needed only to remove this tiny code.

function partial(base, extension) {
  extension.prototype.__proto__ = base.prototype.__proto__; // to enable 'super' reference
  const descriptors = Object.getOwnPropertyDescriptors(extension.prototype);
  delete descriptors.constructor; // must not override constructor
  Object.defineProperties(base.prototype, descriptors);
  
  return base;
}

Using this on TS requires an interface duplicate to extend existing class type, of course.

saschanaz avatar Sep 28 '16 23:09 saschanaz

@SaschaNaz I expect that properties added to constructor through getOwnPropertyDescriptors will be hidden for IDE "autosuggestion" (since they are added at runtime). Remember, Typescript born as a JavaScript with "autosuggestion" (sometimes people call it "stronlgy typed" but really what they like is "autosuggestion").

P.S. Why people need partial classes - codegeneration. But again codegeneration should be supported both by IDE (easy "tool" adjusting to source file, hierarchical result in files explorer, T4 or similar "common codegenerator" support) and in language (partial classes, extension methods). Only after understanding this it is become possible to understand what developers really ask. If you do not see full picture - of course "partial classes" looks like "nonsense".

rpokrovskij avatar Dec 19 '16 13:12 rpokrovskij

@aluanhaddad: but isn't TypeScript's main function is to provide us with language elements which are not present in JavaScript? Why is it a bad idea to have a class splitted into two partial TypeScript files, which will be compiled into a single JavaScript file?

I really do not see the problem with giving a tool to the community. And I am 100% sure there will be devs who will misuse it. But also devs who know exactly how to use it. But don't we have the same situation with any construct of any language?

greendimka avatar Dec 21 '16 08:12 greendimka

+1 for code generation purposes. And I agree with @rpokrovskij, why we choose TypeScript, I can also use JavsScript directly, Just because it's seems like C#, and has ide support.

xiexin36 avatar Dec 23 '16 05:12 xiexin36

@greendimka I don't know how this could work without both diverging from and adding to substantial complexity to ES Modules.

@xiexin36 TypeScript sure seems more like JavaScript than C# to me. There are commonalities between JavaScript and C#, but their notions of class are worlds apart.

aluanhaddad avatar Dec 23 '16 11:12 aluanhaddad

@xiexin36 for code generation you can still use module augmentation (as I noted earlier in this thread). Syntactically it's not as "easy" as partial classes, but you can accomplish the same task.

david-driscoll avatar Dec 23 '16 14:12 david-driscoll

@aluanhaddad Well, it works very simply: partial classes do not change the structure of code in any manner. They just allow us to write definition of the same class in several files (which are compiled into single JS anyways).

greendimka avatar Dec 24 '16 10:12 greendimka

@aluanhaddad Strictly speaking: javascript has no concept of classes (ES6 classes just provide a syntatical sugar). So, if we try to follow the concept of having TypeScript as weak as JavaScript - shouldn't we throw away classes from TypeScript? Shouldn't we simply revert to JavaScript?

greendimka avatar Dec 24 '16 11:12 greendimka

@greendimka ES6 classes and TypeScript classes are one and the same. TypeScript does not aim to add additional constructs to JavaScript's runtime.

ES6 classes are very lackluster. That doesn't mean that JavaScript isn't a powerful language (it is). TypeScript provides static typing to catch errors at design time, provide high quality tooling, allow extremely precise and rigorous specificaiton of component interfaces, and generally improve productivity.

ES6 classes are very lackluster but for TypeScript to introduce its own notion of classes would be in direct violation of its design goals.

Simply avoid classes and your problem will be solved.

Well, it works very simply: partial classes do not change the structure of code in any manner. They just allow us to write definition of the same class in several files (which are compiled into single JS anyways).

And break almost every tool known to man? No thank you.

aluanhaddad avatar Dec 24 '16 11:12 aluanhaddad

@david-driscoll Thank you, I will try it, but I also use Angular 2.0, I wonder if I generate code with @Input or @Output , it will work, anyway I will try it.

xiexin36 avatar Dec 28 '16 15:12 xiexin36

@aluanhaddad it is a pain to see how you hanged on repeating "classes? javascript has no classes". Remove classes from your head, leave only JavaScript, and now listen: developers who use code generation want to have one compilation unit in several files. There are no classes in this language, only functions? OK, we want partial functions. And JavaScript is almost ready for this: functions there can be used before declaration. There we can meet other problems of course (e.g. to be sure that all parts/files are loaded to executiuon environment), but they are solvable, and actually we want to have partial compilation units in TypeScript, not in JavaScrpipt. Typescript is ready for this 100%.

And by the way, TypeScript team, give us partial functions also! And please tell the same to C# team, since we have there "functions in functions" for now. :)

rpokrovskij avatar Dec 28 '16 16:12 rpokrovskij