Suggestion: Extension methods
Allow a declarative way of adding members to an existing type's prototype
Example:
class Shape {
// ...
}
/* ...elsewhere...*/
extension class Shape { // Syntax??
getArea() { return /* ... */; }
}
var x = new Shape();
console.log(x.getArea()); // OK
Personally prefer using static functions and not touching the prototype, e.g.
trait count {
static countCalls = 0;
count() {
countCalls++;
return this.length;
}
}
Compiles to:
trait_count = {};
trait_count.countCalls = 0;
trait_count.count = function(type)
{
return type.length;
}
class foo {
with count;
}
Compiles to:
var foo = ...
/* begin trait_count */
foo.countCalls = 0;
foo.prototype.count = function() {
foo.countCalls++;
return trait_count.count(this);
}
/* end trait_count */
Actually with static modifiers, compiled version would look more like:
trait_count.count = function(static, type, ...arguments)
{
static.countCalls++;
return type.length;
}
var foo = ...
/* begin trait_count */
foo.countCalls = 0;
foo.prototype.count = function() {
return trait_count.count(foo, this);
}
/* end trait_count */
A bit uglier, only if you used 'static'. In most cases, you'd extend the prototype and proxy to a static method. I use traits again since an extension really looks like an anonymous trait.
Highly suggested extension keyword
With the advent of union types, I think the "rewrite call sites" approach is effectively ruled out, as we would no way to emit a call to a method that came in via a union type where one was an extension method and one wasn't (or if they came from two different places).
I think this is thematic with #182 and other places where we want to have something declared in lib.d.ts that you can use as a base class (in an extends clause), but can also add members to via module or interface merging.
One thing we could do is to allow you to add methods to the prototype of a class. Something like this could work:
class Dog {
...
}
extends class Dog {
woof() { /* ... */ }
}
var x = new Dog();
x.woof();
Would emit:
// Begin regular class emit
var Dog = (function () {
function Dog() { }
return Dog;
})();
// End regular class emit
// Begin extends class emit
Dog.prototype.woof = function () {
};
// End extends class emit
var x = new Dog();
x.woof(); // Not altered
A declare extends class would work similarly.
The only restrictions here are that an extends class could not declare initialized instance members as those initializations are emitted into the top of the constructor body. Similarly, you would not be able to add constructors or construct signatures to a class. Since there's no runtime analogue to either of these, the restrictions shouldn't be too bothersome.
Although class extension is great asset to the language, I'm a bit disappointed not to be able to extend an interface in TypeScript while languages tend to evolve to streamline methods of adding new functionality to the interfaces!
extends class Dog {
woof() { /* ... */ }
}
:+1:
I'm a bit disappointed not to be able to extend an interface in TypeScript
Can you clarify? You can extend (subclass) an interface with extends or add members to it (augment) through interface merging.
@RyanCavanaugh My understanding of Extension Methods is how C# does it via static methods or Java with default methods. Lets be honest, the real benefit of having extension methods is with interfaces not concrete classes. Sure you can use interface merging, but then you have to rewrite the implementations of those interfaces you have implemented throughout all your libraries.
IEnumerable<T> in C# is a great example of extension methods, I guess the whole LINQ depends on it. I was thinking with ECMA6 generators, we could have a general Iterable interface containing @@iterator and extend it linq style, could be used on String, Array, Map, Set and Generator.
Now instead, in order to extend an existing interface, we have to merge it with another interface with optional methods (not to break existing code) and extend it to all the classes implementing that interface with an ugly mixin.
Maybe we should find more JS-like way for those "extension methods", for example, bind() or call()...
class Foo { /* */ }
function fooExtensionMethod(this: Foo) { /* */ }
var foo: Foo;
fooExtensionMethod.call(foo);
// This is not so good... "object, method" order, please do not be backward
interface Object {
callFn(func: Function, ...args: any[]); // from an external library?
}
foo.callFn(fooExtensionMethod);
// This is not really foo.fooExtensionMethod, but isn't it just sufficient?
(Burrowing concepts from #229, maybe we also need to solve #212)
I'm :-1: on extending the object prototype. An extension doesn't own the class, it shouldn't be able to mess with it's prototype. The issues @SaschaNaz mentions are real, and IMHO not worth the effort to attempt to surmount, because the number of corner cases in the case of dynamically loaded script is huge.
I would be :+1: on rewriting the call site (just hypothetically speaking), but that would open the door to rewriting call sites in other places (like overloaded functions) which, as far as I understand, is a ship that's already sailed, and I would be :-1: on semantics special-cased to extension methods.
So, while I like the idea of extension classes, I'm not sure there's an effective way to implement them, given the larger constraints already imposed on the language.
I agree with @sccolbert. TypeScript isn't trying to be C# or Java, it's trying to add some sanity to JavaScript. The extensions concept, while cool, is at odds with the way JavaScript classes actually work.
These two statements appear to be at odds with each other.
An extension doesn't own the class, it shouldn't be able to mess with it's prototype.
The extensions concept, while cool, is at odds with the way JavaScript classes actually work.
That's exactly how JavaScript works.
I don't really think that TypeScript should bend over backwards to cater for situations where people are happy to load dodgy scripts from third parties.
Let me rephrase: an extensions concept that requires rewriting call sites is at odds with the way javascript classes actually work, and an extensions concept that modifies the prototype is at odds with the way C#/Java programmers understand extensions.
Yes, C#/Java users want rewriting call sites, but it seems there's no good way to do that. So I still think we may need third-party way to implement really-JS-like extension methods, at least until ECMA people do something here.
interface ObjectStatic {
bindExt(extensionFn: (base: this, ...args:any[]) => any); // Still from potential third-party library
}
Object.prototype.bindExt = function (extensionFn: (base: this, ...args: any[]) => any) {
return (...args: any[]) => extensionFn(this, ...args); // ES6 Spread
}
(Burrowing this type concept from #289)
Now there should be no dynamic script loading, while I don't like the ...args: any[] part.
class Foo { /* */ }
function fooExtensionMethod(base: Foo, arg1: number, arg2: string) { /* */ }
var foo: Foo;
foo.bindExt(fooExtensionMethod)(arg1, arg2);
I think this will provide C#/Java-like extension method. No additional syntax, no rewriting based on type info, but still it gives extensions.
Reading this discussion I still do not understand why extension methods can't be implemented just like the static C# extension methods. I mean why couldn't the compiler could just emit invocation of the static method?
Because TypeScript is not C# and JavaScript is not the CLR.
Here's some code that people would very reasonably expect to work; none of these would be possible if we tried to extension methods with call site rewrites.
// Setup
class Rectangle {
constructor(public width: number, public height: number) {}
}
// Do not be distracted by exact syntax here
extension function getArea(this s: Rectangle ) {
return s.width * s.height;
}
// end setup
// Challenge course begins
interface HasArea {
getArea(): number;
}
function fn1(x: HasArea) {
console.log(x.getArea());
}
fn1(new Rectangle(10, 10));
var a: any = Math.random() > 0.5 ? new Rectangle(3, 3) : { getArea: function() { return 3; } };
console.log(a.getArea());
var s = new Rectangle(5, 5);
var f = s.getArea.bind(s);
console.log(f);
class Square {
constructor(public size: number) { }
getArea() { return this.size * this.size; }
}
var box: Square|Rectangle = /* ... anything ...*/
console.log(box.getArea());
box.getArea.call(box);
var boxes: HasArea[] = [new Square(5), new Rectangle(10, 10)];
boxes.forEach(b => {
console.log(b.getArea());
});
The only plausible language in which we rewrote call sites would have the following restrictions:
- You can't use extension methods as first-class objects, even though that's a very common JavaScript pattern. Only immediate invocations are allowed
- Extension methods aren't used when checking assignability, so you can't use them to add new functionality that is used with any indirection. You can't use an extension method to 'fix' a type to match some interface, even though that's a primary use case
- Extension methods aren't visible when put in a union type, which everyone will assume is a compiler bug
- If the type of a variable accidentally becomes
any, your code will break at runtime with an error you won't be able to diagnose via debugging the code itself. This will look like a compiler bug to most people - You can't use TypeScript extension methods from JavaScript without knowing the special code to write
When you add up all those restrictions, the only real advantage foo.extMethod() has over extMethod(foo) is that there's an extra dot in the extension method call. Plus, it creates a giant trap by having extension method calls on any variables fail. That's not a good deal.
@RyanCavanaugh this is an insanely detailed explanation, thank you! When this thread started, I was sure that extension methods are a very good idea, now I believe we're better of without them (at least for now).
@RyanCavanaugh Have you looked into using a ~ proxy: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Not sure where that proposal stands but fairly optimistic this can work:
class Rectangle {
constructor(public width: number, public height: number) {}
static foo() {
return 'foo';
}
}
Object.seal(Rectangle);
extends(Rectangle, {
static bar(){ return 'bar'; }
getArea() {
return this.width * this.height;
});
Emits
class Rectangle {
....
}
proxy_Rectangle = new Proxy(Rectangle, {
get: function(target, name){
var extension = {
bar: function() { return 'bar'; }
}
return name in extension ? extension[name] : target[name]
}
});
proxy_Rectangle_new_handler = {
get: function(target, name){
var extension = {
getArea: function() { return this.width * this.height; }
}
return name in extension ? extension[name] : target[name]
}
});
// All futur references to 'Rectangle' are wrapped by the proxy
function fn1(x: HasArea) {
console.log(x.getArea());
}
fn1(new Proxy(new Rectangle(10, 10), proxy_Rectangle_new_handler));
proxy_Rectangle.bar()
+1
At present, the primitive types can be extended as:
// Extending String prototype
interface String {
format(...params: any[]): string;
}
// using `any` so consumer can pass number or string,
// might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
var s = this,
i = params.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
}
return s;
};
// Usage:
// 'Added {1} by {0} to your collection'.format(artist, title)
Would be nice to have extension keyword fit in that kind of context as well. :)