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

@greendimka

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.

Not sure what you are trying to say here. But if the overall feeling within the community is that we can achieve the same results using existing language features, then I just need some examples of how to do it. What @david-driscoll posted above is way beyond my comprehension. And doesn't seem to completely solve the problem. In fact, from what I can tell, he misinterpreted my intentions. My primary concern is to code generate the scalar properties of the class, like a pojo or model class. But I need to be able to, in a separate file, or even in the same file, but not within the primary class definition add in the association properties (so that I can paste a newly code-generated primary definition over the original). For example my Contact class from above would get code generated with firstName and lastName. But, in my separate definition is where I would add the definition and initialization of the collection of Address objects.
My code generator only knows the attributes of the class, not the associations, so it cannot code gen the addresses collection -- like was done in david's example.

cosmoKenney avatar Mar 30 '17 16:03 cosmoKenney

@cosmoKenney it wasn't entirely clear where the address should exist. Forgive me to getting the context wrong. I'm just trying to help give the alternatives. There is plenty of functionality that allows similar behavior without putting something into the compiler like partial classes, which have a lot of additional considerations and potential problems to implement both module systems (internal / external).

In your case generating an abstract base class, or interface generation would work, then your other class inherits from that. Then the fact that your class was generated is still hidden.

ie:

// address.partial.ts
export interface IAddress
{
    addr: string;
    city: string;
    state: string;
    zip: string;
}

// address.ts
import { IAddress } from './address.partial';

export class Address
{
    constructor(args: any) {

    }
}
export interface Address extends IAddress{}

// contact.partial.ts
import { IAddress } from './address.partial';

export interface IContact {
    firstName: string;
    lastName: string;
    addresses: IAddress[];
}

// contact.ts
import { Address } from './address';
import { IContact } from './contact.partial';

// Class implementation, do the things here that are not code generated
export class Contact {
    addresses: Address[] = [];

    constructor(args: any) {
        this.firstName = args.firstName;
        this.lastName = args.lastName;
        this.addresses.push( new Address("address?") );
    }

    public somethingAwesome() {
        //
    }
}
export interface Contact extends IContact {}

// main.ts
import { Contact } from './contact';

const contact = new Contact(['my', 'args']);
const {firstName, lastName} = contact;
contact.somethingAwesome();

david-driscoll avatar Mar 30 '17 18:03 david-driscoll

@cosmoKenney: @david-driscoll offers an interesting solution, but it still lacks the ease of real partial classes. As my personal experiments have shown - devs simply do not use "partials" which are made in this way. While it is a good workaround solution, the ease and comfort of partials is not there.

At the moment I do not know how TypeScript compiler works internally. I can only assume that it reads all source files, proceeds them, and outputs JS files. If it is so - I see no problems in reading single class from several source files. If two or more source files of a single class provide conflicting code (f.e. same property defined twice), compiler simply throws an exception. Just as it does if you write syntactically invalid code.

greendimka avatar Apr 01 '17 10:04 greendimka

@greendimka, @david-driscoll I tried to compile David's example from above, and ts doesn't like it:

C:\TestProjects\TypeScriptFakePartialClassTest>tsc -m amd address.partial.ts address.ts contact.partial.ts contact.ts main.ts
address.ts(4,14): error TS2300: Duplicate identifier 'Address'.
address.ts(10,18): error TS2300: Duplicate identifier 'Address'.
contact.ts(7,14): error TS2300: Duplicate identifier 'Contact'.
contact.ts(11,14): error TS2339: Property 'firstName' does not exist on type 'Contact'.
contact.ts(12,14): error TS2339: Property 'lastName' does not exist on type 'Contact'.
contact.ts(20,18): error TS2300: Duplicate identifier 'Contact'.
main.ts(5,8): error TS2459: Type 'Contact' has no property 'firstName' and no string index signature.
main.ts(5,19): error TS2459: Type 'Contact' has no property 'lastName' and no string index signature.

Besides I agree with @greendimka that this is too complex to use hundreds of times in a large application.

cosmoKenney avatar Apr 01 '17 16:04 cosmoKenney

@greendimka I don't know how the compiler works too, but don't underestimate the task. JavaScript is not .NET and modules are not globally available (you should literally import them)

I'd love to see this implemented, but this task brings up several things that needs to be carefully thought about, like:

  • If you define part of the class on a file A, part on file B, which one should contain the full class after tranpiling? A new one should be generated?
  • Should all the files that contains partial stuff export the same class?
  • How to avoid cyclic dependencies if I require the main file on those additional ones?
  • What if I export more things on module than just the class itself?
  • Name conflicts checking?

and so on...

WoLfulus avatar Apr 01 '17 17:04 WoLfulus

@greendimka See my responses below: (EDIT: this was targeted at @WoLfulus, sorry @greendimka):

If you define part of the class on a file A, part on file B, which one should contain the full class after tranpiling? A new one should be generated?

I would be perfectly happy to have file A.js have the full definition, and file B stubbed off. Maybe with a canned comment. Most of us are bundling anyway so the myriad .js files that get bundled become essentially an after thought in the end.

Should all the files that contains partial stuff export the same class?

This is pretty much answered by my response for the first question.

How to avoid cyclic dependencies if I require the main file on those additional ones?

I don't know. Isn't it the module loader's job to recognize this scenario?

What if I export more things on module than just the class itself?

I don't see the problem with this. In other words if B.ts has both a partial definition and some other non-partial classes, then B.js should contain the canned comment as mentioned above, AND the definitions of the non-partial classes. Simple, I think.

Name conflicts checking?

How would you end up with a name conflict? If you mean on the class, then the "partial" keyword would resolve that. But then if two other files both defined classes with the same name, but without the "partial" keyword, the compiler should emit an error about duplicate types -- as it does now. But if you are talking about two partial definitions of the same class defining a property or method of the same name, the compiler should emit an error about duplicate members -- as it does now.

cosmoKenney avatar Apr 01 '17 18:04 cosmoKenney

@WoLfulus, @cosmoKenney has answered well. Just to make it better with your first question (about A and B files): as a language designer, one has a privilege of defining rules. By that I mean that file A may have such code "partial class X" and file B may have such code "partial(fileX) class X", which will produce fileX.js.

greendimka avatar Apr 02 '17 11:04 greendimka

@cosmoKenney

How to avoid cyclic dependencies if I require the main file on those additional ones? I don't know. Isn't it the module loader's job to recognize this scenario?

TypeScript does not have a module loader.

@greendimka

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.

That is not a good idea. For example, have you considered how you will you maintain your fork when dynamic imports are added? Also, plenty of arguments have been made against partial classes. Breaking the source to source correspondence between TypeScript and JavaScript files goes against a key tenet of the language. I imagine that a feature would need to enable a scenario infinitely more valuable than partial classes for that to even be considered. It would likely still be rejected.

@WoLfulus, @cosmoKenney has answered well. Just to make it better with your first question (about A and B files): as a language designer, one has a privilege of defining rules. By that I mean that file A may have such code "partial class X" and file B may have such code "partial(fileX) class X", which will produce fileX.js.

I don't think you are getting your message across. That makes it sound as though you feel that any limitations you ever encounter expressing yourself in any language exist for entirely arbitrary reasons. Also @WoLfulus' questions were not answered, at least not to my satisfaction.

aluanhaddad avatar Apr 02 '17 12:04 aluanhaddad

dons flamesuit

TL;DR: This isn't happening. If you're down here at comment number 189 and want to register your disapproval with that, please do read the entire thread first, because the very good reasons for not adding this have been extensively covered above.

Our interpretation of this situation is as follows:

  • TypeScript already has too many TS-specific class features (constructor property declarations, member initializers, non-finalized decorators, access modifiers, implements, etc.) for something that was really intended to just be "ES6 + Types". Part of that is our fault (our original design direction was generally too OOP) and part of that is ES6's fault (the class proposal moved around a lot five years ago and we ended up having features that didn't make it). Adding yet another TS-specific class feature is another straw on the camel's back that we should avoid if we can.
  • Unambiguously, the future of JavaScript is modules. Partial classes only make sense and operate well in the "global soup" model. Allowing partial classes spanning multiple modules is a recipe for disaster as the loading order is not predictable. Adding a feature that only works well in a global-only universe isn't a good use of time.
  • C# has it but we're not here to reinvent C#. Seriously!
  • The "generated code" scenario isn't compelling on the merits. Any plausible emit for partial classes would restrict property initializers and constructor code to exactly one declaration, and this would be a dealbreaker for .Designer.cs-style setups as both the user code and the generated code would likely need initializers or constructor logic.
  • There are many, many other compositional mechanisms available in JS - mixins, Object.assign, etc.. The scenario that led to this feature in C# was driven by constraints that simply aren't present in JS.
  • The current workaround of interface + prototype.method = ... does enable the generated-code scenario just as well as partial class would. It's weird to write that code by hand but there's no problem for generating code differently, so if you really think a split-file generated code setup is the only way to solve your problem (I'm skeptical) then that method is available to you.
  • We consider ES6 to be the arbiter of "must have" for classes. There's nothing special about TypeScript (other than its appeal to C# programmers) that make it need partial classes any more than non-typed JavaScript would. So if there's some scenario that really knocks it out of the park for adding partial classes, then that scenario ought to be able to justify itself through the TC39 process. If that gains traction we'd be happy to weigh in with input on it, but this doesn't even seem to be on anybody's radar.

RyanCavanaugh avatar Apr 03 '17 22:04 RyanCavanaugh

@RyanCavanaugh about this:

The current workaround of interface + prototype.method = ... does enable the generated-code scenario just as well as partial class would.

As I've mentioned more than once, I'm fine with there being a non-partial, non-c# way of accomplishing what I need, and just ask for a working example. david-driscoll was very helpful, but posted code that doesn't compile. So if you think I can code generate a class with scalar properties only for, for example, first, last name -- like above -- that's fine. I just need a way to add a collection of other types as a property on the class by hand coding that. But I also need a way to handle initialization of that set.

cosmoKenney avatar Apr 03 '17 23:04 cosmoKenney

@cosmoKenney are you site you copied the right code? The second example had interfaces instead of the same class name. I can attach a zip of the code if you like. I was just hesitant because random files on the internet could be bad and didn't want you to think I was posting something malicious 🙂

david-driscoll avatar Apr 03 '17 23:04 david-driscoll

Sorry to hear this, but I respect the design decisions made here. I have a couple of questions if that is ok:

TypeScript already has too many TS-specific class features (constructor property declarations, member initializers, non-finalized decorators, access modifiers, implements, etc.) for something that was really intended to just be "ES6 + Types". Part of that is our fault (our original design direction was generally too OOP) and part of that is ES6's fault (the class proposal moved around a lot five years ago and we ended up having features that didn't make it). Adding yet another TS-specific class feature is another straw on the camel's back that we should avoid if we can.

Considering this, would a possible way forward be to clearly distinguish, organizationally and code-wise, between the pure typing of JS, and the other language constructs that TS offers? I for one love both the typing and the extra language features. As a consumer/developer, I don't care much about about the fact the TS adds stuff that isn't there in JS. Just give me awesome stuff, if TC39 don't want it, I don't care.

If TS would encapsulate these things from each other, maybe that would be easier to reuse and be forked and built upon by projects like SoundScript, instead of replaced?

And then other project could build upon this typing to provide better/other language constructs than are offered by JS.

Unambiguously, the future of JavaScript is modules. Partial classes only make sense and operate well in the "global soup" model. Allowing partial classes spanning multiple modules is a recipe for disaster as the loading order is not predictable. Adding a feature that only works well in a global-only universe isn't a good use of time.

Is it really? Sure that modules would will be a natural part of JavaScript, but what about the main original body of code? I love namspaces and there is no soup in it if done properly. I'm compiling it all into one file, and I have no need of module loaders and in almost all cases no need of asynchronous module loading. Some stuff proposed like https://github.com/Microsoft/TypeScript/issues/420 would only be possible and relevant with namespaces. Are you saying that stuff like this aren't going to happen because we should only use modules? Are namespaces on the road to deprecation?

Elephant-Vessel avatar Apr 04 '17 11:04 Elephant-Vessel

@david-driscoll Thank you, you've already been helpful enough. Since @RyanCavanaugh is the one who keeps closing the issue and stating that there are work arounds, maybe he should provide an example work around.

cosmoKenney avatar Apr 04 '17 15:04 cosmoKenney

I'm also seeing a lot of misconceptions about what partial classes are. It's really a simple construct, and everyone is blowing this out of proportion: https://msdn.microsoft.com/en-us/library/wa80x488.aspx

cosmoKenney avatar Apr 04 '17 15:04 cosmoKenney

Considering this, would a possible way forward be to clearly distinguish, organizationally and code-wise, between the pure typing of JS, and the other language constructs that TS offers? I for one love both the typing and the extra language features. As a consumer/developer, I don't care much about about the fact the TS adds stuff that isn't there in JS. Just give me awesome stuff, if TC39 don't want it, I don't care.

That would be a rewrite of a language and break everyones code.

Also the "Just give me awesome stuff" is very fundamentally different than the design goals for TypeScript. If you just want awesome stuff and don't care about alignment to JavaScript you should choose a different language, like CoffeeScript, Dart, or Haxe. Of course there maybe reasons why those aren't doing as well as TypeScript in adoption...

one who keeps closing the issue and stating that there are work arounds, maybe he should provide an example work around

There are a lot of use cases for what a partial solves. Almost any language construct has lots of use cases it is valid for, but for good reasons, you have to pick and choose.

You keep asking for a specific language feature, as in "I would love a green car" but aren't getting to the crux of the issue, why does the car need to be green? If you explained why your car needs to be green, or be open to the fact that you don't actually care what colour your car is, as long as it provides for your real needs.

I don't see why you feel it is Ryan's obligation to tell you how to repaint your car, just because for valid reasons the car company has decided not to produce green cars.

kitsonk avatar Apr 05 '17 06:04 kitsonk

(Oh and the mixin classes added in TypeScript 2.2 are a good way of accomplishing what I suspect is your real need)

interface Base {}

interface Constructor<T> {
    new (...args: any[]): T;
    prototype: T;
}

interface PartialClass {
    foo(): void;
}

function PartialClass<B extends Constructor<Base>>(base: B): B & Constructor<PartialClass> {
    return class extends base {
        foo() {
            console.log('foo');
        }
    };
}

class MyBase {
    bar() {
        console.log('bar');
    }
}

const MyPartialBase = PartialClass(MyBase);

const instance = new MyPartialBase();

instance.bar();
instance.foo();

kitsonk avatar Apr 05 '17 06:04 kitsonk

@kitsonk mixins are not the same thing.

  • Mixins are self-contained units that can be added to existing classes.
  • Partial classes can access members from any other partial, as if they are part of the same class.

As an exercise, try to implement the following code split with mixins:

partial class Point {
  readonly x: number;
  readonly y: number;
}

partial class Point {
  translate(dx: number, dy: number): Point {
    return new Point(this.x + dx, this.y + dy);
  }
}

tsvetomir avatar Apr 05 '17 07:04 tsvetomir

As an exercise, try to implement the following code split with mixins

So back to the point... So instead of pointing out a language feature, what problem are you trying to address with your example? Because the workaround in TypeScript is easy:

class Point {
  readonly x: number;
  readonly y: number;
  translate(dx: number, dy: number): Point {
    return new Point(this.x + dx, this.y + dy);
  }
}

kitsonk avatar Apr 05 '17 07:04 kitsonk

(and if we are completist, but again, it solves a use, not all use cases)

interface PointBase {
    x: number;
    y: number;
}

interface Constructor<T> {
    new (...args: any[]): T;
    prototype: T;
}

interface TranslatePointPartial {
    translate(dx: number, dy: number): TranslatePointPartial;
}

function TranslatePointPartial<B extends Constructor<PointBase>>(base: B): B & Constructor<TranslatePointPartial> {
    return class TranslatePointPartial extends base {
        translate(dx: number, dy: number): TranslatePointPartial & PointBase {
            return new TranslatePointPartial(this.x + dx, this.y + dy);
        }
    };
}

class Point {
    readonly x: number;
    readonly y: number;
}

const MyPoint = TranslatePointPartial(Point);

const instance = new MyPoint();

instance.x;
instance.y;
instance.translate(1, 2);

kitsonk avatar Apr 05 '17 07:04 kitsonk

@Elephant-Vessel

Considering this, would a possible way forward be to clearly distinguish, organizationally and code-wise, between the pure typing of JS, and the other language constructs that TS offers?

I don't see a way to disentangle the two at this point. One could, in theory, write some language ala CoffeeScript that syntactically transformed to TypeScript and use that higher-level language to add new syntactic features while still using TS's type system, but that'd only get you so far. Just picking one of the many other greenfield compile-to-JS languages instead seems like a better choice if that's the goal.

Are you saying that stuff like this aren't going to happen because we should only use modules? Are namespaces on the road to deprecation?

Namespaces aren't going anywhere, for sure. They're just a naming of a pattern that's already in widespread use and they still make plenty of sense in a world of ES6 modules. Modules are just increasingly the way people organize their code and they have a lot of great side benefits. I'm just saying that partial classes make almost no sense in that world, and it'd be odd to add a fundamentally new organizational pattern that's incompatible with it. If the world were moving in the opposite direction and everyone was like "Global scripts with side effects on load are awesome, everyone party on each others' prototypes", maybe we'd feel differently.

RyanCavanaugh avatar Apr 05 '17 14:04 RyanCavanaugh