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
@danfma I don't see how that's meaningfully different from the dozens of upthread suggestions for similar rewriting of call sites, nor how it addresses the serious problems with that approach.
@RyanCavanaugh, that is just another suggestion like many others above :D
But I still don't get what are the problems with the previous ideas. For example:
let x = 10;
extension function plusOne(this self: number): number {
if (typeof self !== "number") throw new TypeError(); // or anything else
return self + 1;
}
let y = 10.plusOne();
Generated javascript:
var x = 10;
function plusOne(self) {
if (typeof self !== "number") throw new TypeError();
return self + 1;
}
var y = plusOne(x);
- We don't pollute the global variable space;
- If we had a name colliding, with another extension or with a member of the object, when importing we just need to import with another name
import { plusOne as plus1 } from "some/place"; - The only problem that I see is when used in a global scope, but that is a problem that you will have with any library used in global scope;
Then, please, can you point me what you see that I can't see as a problem?
About the extension classes, it has the advantage to allow you to extend with more than one method, but it will make the compiler life hard when having two extension classes with the same function name. One solution for that, is to not resolve automatically when that occurs, so if a name collides, the compiler can raise an error, and let the user resolve, by manually creating the extension by hand, for example.
All of the problems raised at https://github.com/Microsoft/TypeScript/issues/9#issuecomment-74302592 and https://github.com/Microsoft/TypeScript/issues/9#issuecomment-263978824 apply
ok, I will check!
@RyanCavanaugh, I got your points, but I still disagree in some points. Javascript itself is a dangerous language because you can do a lot of things to bug your own code and like the TypeScript team always talks 'TypeScript is JavaScript', so it inherits all the JS problems.
So when you say It's also possible to wire your house with uninsulated 36 gauge wire and bubble gum as long as you're willing to accept it sometimes catching fire, you are right, but you already accepted that too! :D
What I want to say is that even in C# you can have problems by using dynamic or Reflection, so I don't see the difference here.
Anyway, I will stop here and thank you for the long list provided before. 👍
👍
An alternative is to include a forward declaration of the methods you are extending in the class, then modifying the prototype to extend them. For example:
class Greeter {
greeting: string;
say: Function;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
Greeter.prototype.say = function(msg:string) {
alert(msg);
}
let greeter = new Greeter("world");
greeter.say(greeter.greet()); // alerts "Hello, world"
Hope it helps
Honestly, I'd love to see a move away from internal methods at all... some day? Monkey-patching and static helpers only go so far. CLOS and Dylan are good examples of adding methods to classes at any time -- without monkey-patching, and they're lexically scoped. The problem with C# extension methods is that they are statically dispatched, just some syntactic sugar.
If every method was external, you could do something like this:
var _capitalize = capitalize || new Map();
String.addMethod(_capitalize, function() { return this.slice(0, 1).toUpperCase() + this.slice(1); });
"foo".invoke(_capitalize);
// Implementation
Object.prototype.addMethod = function(method, func) { method.set(this, func); }
Object.prototype.invoke = function(method, args) { return method.get(this.constructor).apply(this); };
// Syntax thoughts, where extend creates a locally scoped external function.
extend String { capitalize() { ... } }
"foo".capitalize();
Just some thoughts :) Mike
Some of the examples @RyanCavanaugh wrote on why rewriting call-sites wouldn't work for JS targets, actually works in Haxe (similar to TypeScript and can transpile to JS and others).
See here for one of the examples, in Haxe. Click the build button to see the trace outputs and the JS transpiled output.
Some of his examples don't work, but the Haxe compiler actually manages to catch some of those errors ("x has no method getArea"). However, using the any type (Dynamic in Haxe), will definitely not work, but haxe coders know why they don't work, because in haxe docs, it was stated that we should avoid using Dynamic as it turns off certain type checking features.
To make most of Ryan's examples work in haxe (haven't tried all of them), simply type cast or add type hinting so the compiler knows what to do. Of course, if someone convinced the compiler that a chicken is a duck, but it doesn't quack at runtime, then the problem isn't that the feature is impossible. It is the person who convinced the compiler that the chicken is a duck.
For union types (Square and Rectangle; where one has instance method getArea and the other a static extension getArea), the compiler should show an error because getArea does not really exist for one of them. It should be made that once the type is checked (through an if guard or something), then getArea should work (since within the if statement, the compiler can tell if its a square or rectangle).
Static extension methods can only work if the compiler is able to know the type as it is a compile-time feature. Programmers shouldn't expect something untyped/not properly typed/unverified to take advantage of a compile-time feature that requires type to be known. I think it is possible to implement and that it is also reasonable to expect it not to work if the compiler is unable to infer the type.
@profound7 Consider this code (Haxe):
class BetterSquare extends Square {
public function getArea() {
return this.x * this.y;
}
}
class SquareExtension
{
public static function getArea(square:Square)
{
trace("getArea!");
return square.x * square.y;
}
}
class AThing {
public static function doSomething() {
var qq: Square = new BetterSquare(10, 10);
qq.getArea();
}
}
This results in calling the extension method, rather than the BetterSquare method. This breaks JS runtime semantics preservation -- qq.getArea() must call the instance method on the class because that's what JS does. The TypeScript type system never changes the runtime behavior of code; that is a core principle and a primary guarantee of our language.
(Be aware that any for code you can possibly think about emitting, I can show an example of how to use that behavior to break JS semantics)
Ok, I get it. It mimics C# in a sense that it prioritizes class methods over extension methods. It seems possible to check if the method exists first, but I assume that would incur some overhead.
Personally, I like the idea of being able to shadow class methods. It opens the door to adding functionality, applying bug fixes, logging, security -- AOP cut-points, etc. If they are lexically scoped, there's no risk to other code (other than trojan horses, I guess). Hmm, now I've got to think :)
I've been toying with the idea lately and came up with this form for extension methods. Thoughts?
https://structura.quora.com/Extension-Methods-in-JavaScript
TL;DR:
var _capitalize = Impulse.extend(String, _capitalize, function() {
return this[0].toUpperCase() + this.slice(1);
});
console.log(_capitalize.apply("foo"));
It takes advantage of hoisting and passing the previous method when defining a new one. Applying the method works just like regular functions, but it looks at the type of 'this' and dispatches accordingly. I know there are libraries for multi-methods and stuff, but I wanted to keep it simple.
I use an underscore to not pollute the namespace. lisp-1 vs lisp-2 namespacing debate :)
@mikeaustin it's fine for primitives and classes, but with an erased type system there's no prototype to key off of. It's also not really an "extension method" in the sense of something that appears as a new method of a given type.
I may have mentioned this before on another thread but I think this problem can only be solved with the introduction of a new operator
Calling an existing method on a type
obj.foo();
Calling an extension method on a type
obj::foo();
The latter would translate to...
Extensions.foo(obj);
This allows a distinct differentiation between prototype bound method and extension method calls, without any ambiguity over which is being called in a particular context.
I know there is an ESNext proposal for a bind operator :: so not sure how this would impact this suggestion...would always go with C++'s -> operator if they conflict
Hmm, the universal access principle comes to mind when I see two different ways to call a method. Isn't the purpose of extension methods to hide the implementation?
As to Ryan's message, "extension method" isn't really a formal term outside of C# (I think?) I guess I could call what I'm describing as "method shadowing", which is exactly what it's doing.
@mikeaustin Scala implicits are sometimes colloquy referred to as extension methods. I think the term is fairly well understood.
I agree that using a different token breaks the abstraction.
In spite of the semantics being static in C# the syntactic attraction is precisely the point.
One of the problems I have with the :: is that it doesn't offer any syntactic abstraction over any existing notation.
I feel like it fails at its purpose, which I think is at least in part the very worthy goal of making own versus ambient desirably indistinct, before it even starts.
It would be great to have extension methods but I can't think of a reasonable way.
@aluanhaddad Ahh yes, Scala implicits. Ok, I'll refer to the other way round as "lexically scoped methods". I've been playing a bit more with seamless extension methods in a language I'm prototyping. I've found this works for calling the object method before any extension methods:
(10).toString ? (10).toString() : _toString.apply(10)
And the other way around, lexically scoped methods with fallback to object methods:
typeof _toString === "undefined" ? (10).toString() : _toString.apply(10)
The language does not do static type-checking, so a TypeScript version would probably need a different approach. The above can be / is slow since it has to do that at each call site. But like I said, I'm just prototyping and getting a sense of how it could work.
In both C# and Scala an instance method will always win out in terms of overload resolution so I think that's a good approach.
The problem with applying that approach in TypeScript is not static checking but rather that it is impossible to do it without resorting to type directed emit, which is not an option.
I see the type-directed-emit topic comes up with async/awat, but other than that is it not used anywhere else? Sorry, I don't mean to keep this topic alive forever :)
Side note -- taking your extension methods comments to heart, I've come up with this for my language:
(foo.toString || _toString).apply(foo, []); // Syntax emmited for: foo.toString()
Again, it's not going to be fast, but at least it's short.