TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: Extension methods

Open RyanCavanaugh opened this issue 12 years ago • 170 comments

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

RyanCavanaugh avatar Jul 15 '14 16:07 RyanCavanaugh

@RyanCavanaugh And again, I understand that implementing extensions is probably going to break things in JS but it could be done in a restrictive way first pass where everything has to be in order for it to work right.

electricessence avatar Nov 30 '16 19:11 electricessence

Here is a non-exhaustive list of problems with this approach, as already described at https://github.com/Microsoft/TypeScript/issues/9#issuecomment-74302592

  1. What happens when an extension method is invoked on an expression of type any ? We'll have no idea which method to rewrite to, let alone whether we should at all. A slight change to a .d.ts file that you don't even own might cause an expression to become any and break your program - super bad. How would you even diagnose this? It just looks like a compiler bug. You pulled some new definition files from DefinitelyTyped and now your program stops working at runtime? No.
  2. What happens if you simply reference an extension method, rather than invoke it? The best-case scenario would be a bind invocation, but even this isn't the same (reference identity stops working, for example). Compound this with the previous bullet point.
  3. What happens if you have a union of two objects and two extension methods extending both types in the same way? Or if you have a union where one type has the method built-in and the other has the method from an extension. By all accounts you would expect to be able to invoke the method, but we'd have to somehow generate code that at runtime would distinguish the two objects and pick which method to invoke. In the general case, this is simply impossible. Compound this with the previous two bullet points.
  4. What happens if you e.g. add foo as an extension method to bar and pass a bar to a function that expects { foo(): string } ? We'd have to disallow this because we can't just go rewrite the inside of the function. But now it's completely opaque why you can invoke a method, but you can't pass it to a function that wants to invoke the method on your behalf. It just looks like a compiler bug.

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

  1. What about intersection types? What should happen for a type A & B that has an extension method foo for both A and B with the same name, but different implementations for A.foo and B.foo? I guess you just can't invoke it, but that breaks the contract for intersection types -- now A & B is no longer a substitute for A nor B. Technically we would just pick the first method we found and invoke it, but now your program's behavior would be dependent on the compiler's internal ordering of the constituents of intersection types, which is not at all specified (would the type B & A now need to be distinct from A & B ?)
  2. We would be strictly unable to ever change anything in the type system again without fear of breaking someone's program's behavior. Overload resolution, for example -- we really want to tweak the rules here, but now returning an A instead of a B due to resolution changes might result in a different method being invoked at runtime and cause a previously-working program to fail (or worse, corrupt data)

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

@RyanCavanaugh all valid points that I'm aware of. Hence why I'm suggesting it may require a heavy amount of restrictions to work. Compile time collision detection would be essential, and not optional.

  • Import two extension libs that directly collide because their signatures match/overlap? Compiler disallows.
  • Using any as the type in an extension's this parameter? Compiler disallows.
  • Applying an extension to a value that is of any could be warned against or simply ignored. Yes, this might look funny. But I would suggest a compile warning by default if an extension is imported and the any value has it applied. Again, extensions would be a 'special' feature. You'd need to then have a compiler flag to say "ignoreExtensionAny".
  • At first you could be very explicit with extensions that it has to be a perfect match or they won't be applied. So any unions would fail. Intersections for the most part shouldn't, but I get that intersections are a bit funny too.

electricessence avatar Nov 30 '16 20:11 electricessence

  1. Basic JS premises like bar["foo"] !== undefined implying "foo" in bar are now broken, unless we would want to somehow rewrite the in operator in certain cases (how??). It's not clear how you could do this in a way that doesn't fundamentally change the runtime behavior of JS in many cases.
  2. Basic JS premises like const x = "foo"; bar[x](); being identical to bar.foo(); are now broken, unless we want to start doing aggressive constant folding, but even that wouldn't be sufficient. It's hard to imagine keeping a straight face on the "all JS is TS" promise here.

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

Applying an extension to a value that is of any could be warned against or simply ignored.

This is circular logic. How do you know that an invocation of a method of an any expression is an extension method call rather than a normal call? You don't, because it's any.

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

Yeah, like # 8 is great example. But I'm suggesting that those are not cases where extensions be valid. It would have to be a function, and it would have to be dot notation.

electricessence avatar Nov 30 '16 20:11 electricessence

You don't, because it's any.

any does throw a wrench in the gears. Maybe the use of any is somehow disallowed in modules that use extensions.

electricessence avatar Nov 30 '16 20:11 electricessence

I guess ultimately, I don't see it as impossible. It's just problematic or difficult to get right.

electricessence avatar Nov 30 '16 20:11 electricessence

I mean, it's possible as long as you're willing to accept a feature that is outright dangerous to use, has non-working scenarios that look like compiler bugs, restricts the use of many common JS idioms, requires type-directed emit, doesn't interop with plain JS at all, and prevents the TS type system from ever changing again.

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. :wink:

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

@RyanCavanaugh could you provide a sort of similarity in terms of how dangerous extension methods are in C# vs TS? - I mean we're all talking about extension methods, essentially because they're in C#, and we'd like to see them in TS...

...brb, need to go rewire my house quickly...I can smell burning gum!

MrMatthewLayton avatar Nov 30 '16 20:11 MrMatthewLayton

@RyanCavanaugh at your last comment: I have to respect consistency. So I agree, adding a feature that creates confusion is bad. Thank you for the in-depth reply.

electricessence avatar Nov 30 '16 20:11 electricessence

@series0ne if I may help out here and summarize... Just the notion of any is enough to create a serious issue. There's just too much opportunity for collision. And as I chatted with Ryan about, you could solve these headaches, but it would create different headaches and inconsistencies that make it not worth it.

electricessence avatar Nov 30 '16 20:11 electricessence

There's no danger in C# because C# a) resolves all call sites at compile-time, b) uses a nominal type system, c) uses an explicit opt-in mechanism to provide dynamic method calls (in which extension methods simply don't work), and d) doesn't allow method references in typeless contexts. Consider this C# code:

            IEnumerable<int> enumer = null;
            List<int> list = null;
            Func<int> x = enumer.Count;
            int y = list.Count;

The IL for the last two statements there is very different!

We also have to consider code like this

            var z1 = enumer.Count; // Error
            var z2 = list.Select; // Error

C# rightly errors on these, but TS really can't - that's valid JS and we have to emit something.

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

@RyanCavanaugh, maybe you've already done so, but I think this topic is worthy of a blog post. :P "Why JS/TS cannot have extensions"

electricessence avatar Nov 30 '16 20:11 electricessence

Essentially it seems then, that we will simply have to stick to statically bound method calls in TypeScript, the same way we would have done it with C# before extension methods :(

MrMatthewLayton avatar Nov 30 '16 20:11 MrMatthewLayton

The bind operator https://github.com/tc39/proposal-bind-operator is very promising and would accomplish nearly all the extension method scenarios quite cleanly. So keep some hope :wink:

RyanCavanaugh avatar Nov 30 '16 20:11 RyanCavanaugh

😯 @RyanCavanaugh you would not believe the post I'm writing right now...which, without seeing the bind operator proposal, is virtually identical (great minds...?) here goes...

Essentially the only way I can see this working is to introduce an operator which instructs the TypeScript compiler, this is an extension method call! This borrows from C++

Example

class StringExtensions {
    public static isUpper(this string value): boolean {
        return value.toUpperCase() === value;
    }
}

var x: string = "Hello World";

x->isUpper();

//or

x::isUpper();

Even if isUpper was already a member of String.prototype, TypeScript would know to use the extension method, not the prototype bound method, unless the operator changed.

In terms of dealing with things like union or intersection types, I think the only solution would be to make the extension method invariant; for example

var x: string | number = 0;

x::isUpper(); // Error, cannot call this because the extension method expects type "string"

Thus, you would require an overload to allow this behavior.

Again, I did NOT read about the bind operator before writing this, and it's just escaped my noodle, so there are likely some gaping holes!

P.S. probably want to go with ::, and not -> because TS already has => and =>/-> look too similar.

MrMatthewLayton avatar Nov 30 '16 21:11 MrMatthewLayton

Yeah, the bind operator would go a long way toward giving us extension-like behavior. It still isn't monkey-patching, won't fix types like you might want, and has its own challenges for integrating into TypeScript, but not impossible challenges.

TypeScript would have to start tracking the type of this in a function more aggressively, for instance. We already have that ability to explicitly specify its type with the fake this parameter, but it would have to be expanded to automatically infer the type of this for functions pulled from class prototypes and the like.

Anyways, I still think TypeScript can benefit from a compile-time abstraction for associating behavior to types, especially since it has one for structure. Many current JavaScript libraries are created in a manner that would work well with it and they wouldn't be helped by the bind operator. Also, it would reduce the compulsion to duplicate function implementations in separate classes or use unintuitive forms of inheritance, all just to get the nicer feeling method-call syntax. I've done that before...

I think I may submit my current proposal under the terminology the programming language D uses, 'Uniform Function Call Syntax', and try to keep the use of the words 'extension' or 'extends' to a minimum.

JHawkley avatar Dec 01 '16 02:12 JHawkley

Then maybe the Scala extensions would be help this kind of problem. In Scala, I can define a class which will provide methods and properties to an instance. So, in resume:

extension class MyExtension(target: any)
{
    printHello() {
        console.log("DO MY CODE");
    }
}

var something: any = ...;

something.printHello();

could be transformed to this equivalent:

class MyExtension(target: any)
{
    printHello() {
        console.log("DO MY CODE");
    }
}

var something: any = ...;
var something$MyExtension = new MyExtension(something);

something$MyExtension.printHello();

and then to the equivalent javascript code. Thus, In the end:

  • We won't have any problem with name collision because to use an extension I need to import it;
  • All the transformation is done by the compiler;
  • Yes, we have problems with additional allocation of objects when creating a new extension, but that is a feature that can or can't be used, so we just need to used it wisely;

danfma avatar Dec 01 '16 19:12 danfma