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!"; }
}
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.
@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.
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 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
}
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.
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.
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!
I'm going to try out your TypeScriptBuilder ;)
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...
- If I want to use
MyClassI have to import it fromMyClass.ts - When compiled,
MyClass.partial.tswill generate a javascript which extendsMyClass.prototypelike showed here before. But it exports a function which receives the prototype to be extended. MyClass.partial.tsis imported inMyClassafterMyClasshas 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 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.
It would be an enhancement to the type system, with the partial classes use case falling out of that enhancement.
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();
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: MyClasssyntax.- 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.
- This can be easily solved in generated code by casting to
- 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 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.
@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.
What if someone does not use modules?
@pankleks partial classes are still a bad idea.
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.
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?
Barring ES6,
We cannot bar ES6 when discussing TS language features, because one of the TS goals is to follow current/future ES spec.