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
Highly suggested :+1: This would add methods to existing types without creating a new derived type or modifying the original type and it would definitely make sense in linq to typescript query operators
The original issue at codeplex had pretty much lots of votes: https://typescript.codeplex.com/workitem/100
:+1:
:+1:
Perhaps this can be used in an ambient context as well :
declare module foo{
class A{}
extension class A{}
}
extending A { } for short? I think we don't need class there.
A couple of questions: What would be the compiled js like? And how would be the runtime interoperability with the existing class? Extension methods in C# are static methods with syntactic sugar for instance method call syntax with the first parameter specifying the type the method operates on. Which brings some benefits beside the instance call syntax:
- Extension methods can be called directly as static method call
- Extension classes are not newable
- There could be different extension methods on the same type in the same namespace as long as each class containing extension methods has its own identifier
Having considered extension class syntax, is extension class actually a class or a module at runtime? How do you translate this in a body of an extension method at runtime? (Function.apply, Function.call maybe?) And how would extension methods be like on an interface which I believe is the most commonly use case for extension methods?
While the naive implementation of extension methods is probably like this:
extension class Shape { // Syntax??
getArea() { return /* ... */; }
}
console.log(x.getArea()); // OK
Compiling to:
// js
var _Shape = {
getArea:function() { return /* ... */; }
}
console.log(_Shape.getArea.call(x));
I think due to first-class functions in JS there is a problem with this approach:
extension class Shape { // Syntax??
getArea() { return /* ... */; }
}
var x = new Shape();
var y = new Shape();
console.log(x.getArea); // Function or undefined?
x.getArea.foo = "bar";
console.log(y.getArea.foo); // "bar" or undefined?
If extension methods are to be implemented, there would probably have to be restirictions on accessing/changing their properties.
Considering "class" syntax
extension class Shape { // Syntax??
getArea() { return /* ... */; }
}
In my opinion, one of the common uses of extension methods is to make them work on interfaces, not just classes, so you could do something along the lines of
interface IPoint {
x:number;
y:number;
}
class Point implements IPoint {
constructor(public x,public y) {
// ...
}
}
var p1:Point = new Point(0, 50);
var p2:IPoint = { x:32, y:32 };
console.log(p1.getLength()); // extension method
console.log(p2.getLength()); // same extension method
If possible, I think C#-like extension methods would work best:
extension function getLength(this p:IPoint):number {
return Math.sqrt(p.x*p.x + p.y*p.y);
}
// another extension method with the same name but for different class
extension function getLength(this s:string):number {
return s.length;
}
console.log(getLength); // compiler error
console.log(p1.getLength); // Function or undefined or compiler error?
console.log(p1.getLength.foo); // compiler error
p1.getLength.foo = "bar"; // compiler error
Compiling to:
// js
function _IPoint$getLength() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
function _string$getLength() {
return this.length;
}
console.log(_IPoint$getLength.call(p1)); // OK
console.log(_IPoint$getLength.call(p2)); // OK
Hmm, I thought that this proposal was just to extend prototypes.
class A {
foo() {
}
}
extending A {
bar() {
}
}
Compiling to:
var A = (function () {
function A() {
}
A.prototype.foo = function () {
};
return A;
})();
A.prototype.bar = function () {
};
I don't think extension methods should be implemented by adding a function to the prototype! For one thing extending the prototype of built in types, is considered dangerous, 3rd party libraries may also add a method with the same name to the prototype, causing the behavior to depend on which JS file was loaded last, or worse you might overwrite the existing built-in methods! And for another, there's no way to have different method overloads for the extension methods defined in different modules! More importantly, prototype extending works only for concrete classes, in a sense, no interface or declared class extension methods!
I still agree with @SaschaNaz . There are issues surely but for :
3rd party libraries may also add a method with the same name to the prototype, causing the behavior to depend on which JS file was loaded last, or worse you might overwrite the existing built-in methods
this would be caught by name collision in the lib's .d.ts file and your custom.d.ts file.
More importantly, prototype extending works only for concrete classes, in a sense, no interface or declared class extension methods
I don't expect it there to be any codegen for ambient declarations. PS: If you ambiently say something is a class TypeScript already assumes it has a prototype. e.g.
declare class Foo{}
console.log(Foo.prototype); // Compiles fine
So adding to the ambient prototype is consistent with what already exists.
Perhaps examples of your concerns (if still there) would help.
this would be caught by name collision in the lib's .d.ts file and your custom.d.ts file.
This is only true if there is .d.ts metadata for every 3rd party library (which is not) and only when .ts files are being compiled together (ie. in the same project). Besides there are lots of .js libraries as part of server-side environment which are being injected into dynamic pages at runtime (take asp.net server controls for example)
If you ambiently say something is a class TypeScript already assumes it has a prototype
Ambient class declaration does not have implementation, which is not the case for extension methods, unless extension methods for ambient class declarations are being erased in the compiled .js (which I believe is counterproductive to it's purpose), the program might break at runtime!
And how about interfaces? To extend an interface new methods has to be added to the interface, but changing the interface by adding new methods would break compatibility with existing consumers! Take IEnumerable<T> in C# for example, I cannot imagine how many classes are already implementing this interface! Without having extension methods on interfaces, there could be no LINQ as we know it!
I believe the real advantage of extension methods is being loosely coupled with the existing type, e.g.
Array.prototype.join = function (inner, outerKeySelector, innerKeySelector, resultSelector) {
};
The above example is supposed to add linq-like join operator for arrays, however having altered the prototype, we have lost the built-in join method. Having extension methods separated in a concrete different method actually benefits better method overloading.
There's also a big benefit with generic extension methods which is reducing the need for a common base class. The following is an example of using generic extension method in C#:
public static bool In<T>(this T obj, params T[] source)
{
return new HashSet<T>(source).Contains(obj);
}
Which you can simply use:
var o = 1;
o.In(1, 2, 3, 4, 5); /// true
Great discussion so far.
There's a key decision point here on this feature, which is how the emitted code would work. I see two options based on what's been discussed so far
Example code I'll use
class Square { /* ... */ }
extension function getArea(this: Square) { // First param must be 'this'
return this.width * this.height;
}
var x = new Square(10, 10), y: any = x;
console.log(x.getArea());
console.log(y.getArea());
Add to .prototype
/* Regular emit for 'Square' here */
Square.prototype.getArea = function() {
return this.width * this.height;
}
var x = new Square(10, 10), y = x;
console.log(x.getArea());
console.log(y.getArea()); // Succeeds
Pros
- Works even if type information is missing (
y) - Accurately models many existing libraries' behavior
Cons
- Doesn't work for interfaces, which is probably a primary use case
- Adding to
prototypeis often a bad idea, especially for built-in objects
Rewrite call sites
/* Regular emit for 'Square' here */
__Square_getArea = function() {
return this.width * this.height;
}
var x = new Square(10, 10), y = x;
console.log(__Square_getArea.call(x));
console.log(y.getArea()); // Fails
Pros
- Works on interfaces as well as classes
- Don't mess around with
prototype, so it's safe for built-in types
Cons
- Unclear what it means to use this method in a non-call position
- Fails unexpectedly when strong type information is absent
- Doesn't model existing JS library behavior; we'd still then need an alternate syntax for those
@RyanCavanaugh I would alter the example code, to use the type parameter for the extension method instead of dynamic binding of this :
class Square { /* ... */ }
extension function getArea(this square: Square) { // First param must be 'this'
return square.width * square.height;
}
var x = new Square(10, 10);
console.log(x.getArea());
Which would translate to this:
function getArea(square) {
return square.width * square.height;
}
var x = new Square(10, 10);
console.log(getArea(x));
So that the function behave like a static helper method and it's valid to call it non-instance way. However still fails when strong type information is not present. You can call the extension function explicitly:
var x = new Square(10, 10), y:any = x;
console.log(x.getArea()); // Succeeds
console.log(getArea(y)); // Succeeds
I like the suggestion of @KamyarNazeri, this can be used on an enum (or an union in the feature) too. This code is also faster than a prototype call or a .call().
Would the extension keyword be necessary? Since you already add this to the first argument.
@ivogabe +1 for mentioning enum, I would like to also mention that using static functions, you can call methods on objects that are null, e.g. isNullOrEmpty for string type. small things yes, but darn useful
How about this?
class Square { /* ... */ }
function getArea() joins Square {
return this.width * this.height;
}
var x = new Square(10, 10);
console.log(x.getArea());
Translates to:
/* Regular emit for 'Square' here */
__Square_getArea = function(_this) {
return _this.width * _this.height;
}
var x = new Square(10, 10);
console.log(__Square_getArea(x));
PS: Or without renaming, as @KamyarNazeri did. I like the non-instance way.
function getArea(_this) {
return _this.width * _this.height;
}
var x = new Square(10, 10);
console.log(getArea(x));
I want to emphasize the danger of the "rewrite call sites" approach:
class Square { /*... */ }
/* Extension method getArea, syntax irrelevant */
function process(callback: (n: Square) => void) {
/* invoke callback on a variety of Squares */
}
process((n) => {
n.getArea(); // Succeeds
});
process(((n) => {
n.getArea(); // No compile error, fails at runtime
}));
var x = new Square(), y: any;
var arr1 = [x];
arr1[0].getArea(); // Succeeds
var arr2 = [x, y];
arr2[0].getArea(); // No compile error, fails at runtime
There are very strong reasons TypeScript avoids rewriting code based on type information (see https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals). No one wants to get in a situation where adding a non-observed element to an array or adding extra parentheses around a function could causes program to start to fail at runtime.
@RyanCavanaugh Seriously I don't understand why by adding extra parenthesis around a lambda function, the runtime infers variable n as any?
It's like to evaluate variable b's type argument in the following code as any (which is not)
var a = function (n: number): void { }
var b = (a); // here b accepts number!
As for the latter example, I believe no-one expects an extension method to work when boxing variable to another type (here any due to the type mismatch in the array). At least this is how C# / VB work, with boxing to another type, there's no extension method! Only they don't compile in such situations.
We explicitly decided parenthesizing an expression should be the way to opt out of contextual typing or else you were always at the mercy of the inference algorithm even if it was wrong/incomplete.
Maybe we can choose separate syntax to call those functions.
class Square {
foo() {
}
}
function getArea() joins Square {
return this.width * this.height;
}
var x = new Square(10, 10);
var y: any = x;
console.log(x calls getArea()); // Succeeds
console.log(y calls getArea()); // Succeeds both in compiling and in runtime.
console.log(x.getArea()); // Fails, this is only for functions in prototype
console.log(x calls foo()); // Fails, this is only for extension functions
PS: Fixed to allow y calls getArea().