Closed
Description
ORIGINALLY PROPOSED IN http://typescript.codeplex.com/workitem/838
Traits, as "compile-time" partial classes, would perfectly fit with TS ideology and resolve problems of multiple inheritance/mixins.
Traits in Scala: http://en.wikibooks.org/wiki/Scala/Traits
Traits in PHP: http://php.net/trait
I propose minimal traits similar to PHP implementation.
trait FooTrait {
// same as class definition, but no constructor allowed, e.g.:
public foo() {
return "foo";
}
private bar() {
return "bar";
}
}
class Foo {
import FooTrait; //not insisting on exact keyword and syntax, just smth to start with
// ...
}
class Bar {
// rename methods:
import FooTrait(foo => tfoo, bar => tbar);
// and to include another trait, there is another import line:
// import BarTrait;
// ...
}
The code above could be compiled to JS below (can be optimized, just showing the main idea):
var FooTrait = (function () {
function FooTrait() {
throw "Cannot instantiate trait FooTrait";
}
FooTrait.prototype.foo = function () {
return "foo";
};
FooTrait.prototype.bar = function () {
return "bar";
};
return FooTrait;
})();
var Foo = (function (_super, FooTrait) {
function Foo() { }
Foo.prototype.foo = FooTrait.prototype.foo;
Foo.prototype.bar = FooTrait.prototype.bar;
return Foo;
})(undefined, FooTrait);
var Bar = (function (_super, FooTrait) {
function Bar() { }
Bar.prototype.tfoo = FooTrait.prototype.foo;
Bar.prototype.tbar = FooTrait.prototype.bar;
return Bar;
})(undefined, FooTrait);
Unresolved name conflicts should raise a compile time error.
I think it would be a great advance for the language. But the proposal has more than one year made (in codeplex) and has not yet been implemented.