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

Functions is what we want to avoid with the notion of class. Modules or namespaces bring simple extensibility and have not the same expresiveness as TypeScript's classes. Also, a namespace or a module cannot be instanciated. They do not serve the same purpose as classes.

yahiko00 avatar Jul 25 '16 05:07 yahiko00

@aluanhaddad I see what you mean regarding modules. A possible solution would be to allow only one of the files to export partial class while the rest contain only partial class definitions. You import it from the place its exported. From your example:

app/my-class.ts

export partial class MyClass {
    firstName = "John";
    lastName = "Smith";
}

app/my-class.part.ts

partial class MyClass {
    get fullName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

app/main.ts

import { MyClass } from './my-class';

What's missing is a syntax to let the compiler know where to locate the parts. This is not an issue with C# where you process all files at once. This might be a special syntax, as the one used for declaration merging.

It's not required for partial classes to allow arbitrary definitions. They can be limited only to methods, properties and constructors, for example. This makes execution order insignificant and allows the compiler to throw an error if a member is duplicated.

tsvetomir avatar Jul 25 '16 08:07 tsvetomir

I fail to see why Module Augmentation is not valid for these scenarios. It's worked very well for us with Rxjs5.

You simply create your base class, and then with your code generation, generate all the augmented methods you need on top of the base class. It doesn't matter if the generated code is pretty, no humans are supposed to write it.

Is it a perfect replacement for partial classes? I suppose not, but I don't see partial classes happening unless ECMAScript decides JavaScript needs them. The semantics for how partial classes are linked together between external modules alone hurts my head.

david-driscoll avatar Jul 25 '16 12:07 david-driscoll

@david-driscoll to make it even better, added methods can have a this: argument declared, for a stronger type-checking.

In the cited example of Module Augmentation:

// observable.ts stays the same
// map.ts
import { Observable } from "./observable";
declare module "./observable" {
    interface Observable<T> {
        map<U>(f: (x: T) => U): Observable<U>;
    }
}
Observable.prototype.map = function (this: Observable, f) {
    // here "this" has the shape of the "Observable" class
}

nippur72 avatar Jul 25 '16 14:07 nippur72

Yeah. Rxjs doesn't quiet use it yet, because it's a 2.0 feature, and 2.0 hasn't been released yet. It's on my hit list later.

david-driscoll avatar Jul 25 '16 18:07 david-driscoll

I see what you mean regarding modules. A possible solution would be to allow only one of the files to export partial class while the rest contain only partial class definitions. You import it from the place its exported. From your example:

app/my-class.ts

export partial class MyClass {
    firstName = "John";
    lastName = "Smith";
}

app/my-class.part.ts

partial class MyClass {
    get fullName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

I like the syntactic concept but the problem is that you have just introduced a new kind of source file that is consumed as a sort of implicit module, looks like a script, and has to be loaded in a specific manner.

What's missing is a syntax to let the compiler know where to locate the parts. This is not an issue with C# where you process all files at once. This might be a special syntax, as the one used for declaration merging.

Declaration merging works for declarations, not source files.

It's not required for partial classes to allow arbitrary definitions. They can be limited only to methods, properties and constructors, for example. This makes execution order insignificant and allows the compiler to throw an error if a member is duplicated.

All of these are commonly order dependent.

Edit: That is to say that defining them modifies the class.

aluanhaddad avatar Jul 25 '16 19:07 aluanhaddad

Probably someone mentioned this already, but another useful case is when you generate part of the class from some code generator, then you wish to manually add some more code directly in your implementation. You don't really wish to do mixing or derived class. It's still one class - just part is generated automatically other part manually.

BTW: if someone needs to generate TS types from C# classes you can check TypeScriptBuilder

Thanks for considering this!

pankleks avatar Jul 28 '16 10:07 pankleks

I'm going to try out your TypeScriptBuilder ;)

yahiko00 avatar Jul 28 '16 11:07 yahiko00

My suggestion...

What if the compiler didn't try to find all parts? What if I had to import other parts and controlled everything?

/MyClass.partial.ts

export partial class MyClass {
    firstName = "John";
    lastName = "Smith";
}

MyClass.ts

// v- this would NOT throw an error because the definition is marked as partial
import { MyClass } from "./MyClass.partial";

export class MyClass {
    get fullName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

Then...

  1. If I want to use MyClass I have to import it from MyClass.ts
  2. When compiled, MyClass.partial.ts will generate a javascript which extends MyClass.prototype like showed here before. But it exports a function which receives the prototype to be extended.
  3. MyClass.partial.ts is imported in MyClass after MyClass has been defined and it's extend function is called.

On a side note... there's nothing preventing me from generating the compiled code directly. But I loose all the greatness of Typescript.

svallory avatar Sep 06 '16 19:09 svallory

@svallory I think that's definitely the right approach here. Specifically because you say the generated code will export a function which would cause the augmentation, it would work even with asynchronous imports because the functions can be called in the necessary deterministic order.

More generally, and I forget the issue where it was referenced, if assignments to the class prototype affected the shape of the class, there could be many benefits. This would improve mixin libraries, make decorators far more useful, and generally encourage less vertical hierarchies.

It could be tricky for the compiler to track all of this, but it probably could be made to work by being explicit as you suggest.

aluanhaddad avatar Sep 06 '16 23:09 aluanhaddad

It would be an enhancement to the type system, with the partial classes use case falling out of that enhancement.

aluanhaddad avatar Sep 06 '16 23:09 aluanhaddad

I've did it like the following:

I've did it like the following:
file1.ts
interface ifoo{
   a():void;
}
class foo implements ifoo{
   a() { /*do something*/ }
}
file2.ts
/// <reference path="file1.ts" /> //not necessary
interface ifoo{
   b():void;
}
foo.prototype.b =() => { /*do something*/ }
file3.ts
/// <reference path="file1.ts" /> //not necessary
interface ifoo{
   c():void;
}
(<ifoo>foo.prototype).c =() => { /*do something*/ }
consumer.ts
/// <reference path="file1.ts" />
/// <reference path="file2.ts" />
/// <reference path="file3.ts" />
let f = new foo();
f.a();
f.b();
f.c();

wongchichong avatar Sep 08 '16 15:09 wongchichong

Module Augmentation still solves 90% of the problem here. Given @svallory's examples.

/MyClass.partial.ts

export partial class MyClass {
    firstName = "John";
    lastName = "Smith";
}

MyClass.ts

// v- this would NOT throw an error because the definition is marked as partial
import { MyClass } from "./MyClass.partial";

export class MyClass {
    get fullName(): string {
        return this.firstName + ' ' + this.lastName;
    }
}

The module augmentation would be something like...

MyClass.ts

export class MyClass {
    firstName = 'John';
    lastName = 'Smith';
}

MyClass.generated.ts

import { MyClass } from './test';

Object.defineProperty(MyClass.prototype, "fullName", {
    get(this:MyClass) {
        return this.firstName + ' ' + this.lastName;
    }
});

declare module './test' {
    interface MyClass {
        readonly fullName: string;
    }
}

It's a little more verbose than a partial class, but really the partial class would just be syntactic sugar for this implementation.

The only gotchas today you don't have would be:

  • You cannot access private or protected fields using the this: MyClass syntax.
    • This can be easily solved in generated code by casting to any.
    • Perhaps this is something that can be added, such that you can access protected members of this. There may be other rules around that.
  • The generated code looks a little more intimidating , but for the consumer, once things have been augmented, they would never know the difference.

EDIT: Keep in mind, this is TS 2.0+ syntax.

david-driscoll avatar Sep 08 '16 15:09 david-driscoll

@david-driscoll I agree. I think that is simpler and I like that it doesn't introduce the additional syntax. As you know, I am opposed to partial classes as a specific language feature, but I do think it would be beneficial if TypeScript tracked assignments to prototypes in general and refined the shape of the object accordingly. I think your approach is the right way to split classes across multiple files.

aluanhaddad avatar Sep 09 '16 00:09 aluanhaddad

@wongchichong Your example uses global class names and /// <reference path="..."/>. I don't think that will scale well, although you could use a namespace to improve the situation. Code written as modules (that is external modules) is a very different beast because it involves a loader which needs to be aware of dependencies which are order dependent and implicit. That is why @svallory's suggestion is valuable, it requires a very minimal amount of manual wiring which makes the dependencies explicit.

aluanhaddad avatar Sep 09 '16 00:09 aluanhaddad

What if someone does not use modules?

pankleks avatar Sep 14 '16 11:09 pankleks

@pankleks partial classes are still a bad idea.

aluanhaddad avatar Sep 14 '16 15:09 aluanhaddad

To clarify, I mean they are bad idea in language like JavaScript where class declarations are imperative, not declarative. Even if you're using namespaces, you're going to end up breaking your code into multiple files which means you to have to depend on the script tag order of those files for this to work at all.

In a language like C#, partial classes work well but that's because they're fundamentally different from classes in JavaScript.

It's mportant remember that in JavaScript, class declarations are not even hoisted let alone declarative.

aluanhaddad avatar Sep 14 '16 15:09 aluanhaddad

Barring ES6, the "class" concept is defined by TS. JS has no notion of a class at all. So its up to TypeScript to decide what a class can be, no?

tsvetomir avatar Sep 14 '16 15:09 tsvetomir

Barring ES6,

We cannot bar ES6 when discussing TS language features, because one of the TS goals is to follow current/future ES spec.

saschanaz avatar Sep 14 '16 15:09 saschanaz