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

This turned to be more complicated that it looked like! Having rewrite call sites comes handy when coding, however I agree that the code might break at runtime! I've seen lots of javascript developers debugging their code in the browser developing tools which also fails using rewrite call sites. But the ability to extend interfaces is so good that you can't simply ignore it, so probably we are addressing two different problems here:

  • Extending a class (by using extension methods)
  • Extending interfaces (including built-in types since built-in types are represented as interfaces in the typescript runtime)

Maybe we could consider Java 8 default methods (or as they are often called defender methods) to extend an existing interface. Of course default methods in an interface could translate back to prototype in the emitted js code:

interface ISquare {
    width: number;
    height: number;
    default getArea(): number {
        return this.width * this.height;
    }
}

class Square implements ISquare {
    constructor(public width: number, public height: number) {
    }
    // no need to implement getArea here
}

var x = new Square(10, 10), y: any = x;
console.log(x.getArea());  // Succeeds
console.log(y.getArea());  // Succeeds

which would compile to:

var Square = (function () {
    function Square(width, height) {
        this.width = width;
        this.height = height;
    }
    Square.prototype.getArea = function () {
        return this.width * this.height;
    };
    return Square;
})();

knazeri avatar Aug 16 '14 16:08 knazeri

default methods in an interface could translate back to prototype in the emitted js code

This interface looks more like an abstract class. #6

basarat avatar Aug 17 '14 02:08 basarat

This interface looks more like an abstract class.

Only a class might already inherit another base class, I think the real benefit with interface extension comes with multiple inheritance simulation.

knazeri avatar Aug 17 '14 07:08 knazeri

Maybe we could consider Java 8 default methods

The difference is that interfaces in TypeScript can be used without classes. How would the following code compile?

interface ISquare {
    width: number;
    height: number;
    default getArea(): number {
        return this.width * this.height;
    }
}
var square: ISquare = {
    width: 100,
    height: 50
};
console.log(square.getArea);

Maybe we can choose separate syntax to call those functions.

Maybe call the function like this: (since this syntax already exists)

getArea(square);
// instead of
square calls getArea();

ivogabe avatar Aug 17 '14 09:08 ivogabe

Maybe call the function like this: (since this syntax already exists)

Chaining would become uncomfortable in that case. Example:

var num = new Number(0);
function plus(input: number) joins Number {
  return this.valueOf() + input;
}
num.plus(3).plus(3).plus(3);
num calls plus(3) calls plus(3) calls plus(3); // Well... not very good to see. Hmm

versus

plus(plus(plus(num, 3), 3), 3);

...while the rewritten JavaScript will be anyway plus(plus(plus ... form.

Edited:

num->plus(3); // Syntax that looks like the C++ one but for extensions?

or

num<-plus(3); // function 'plus' joins to 'num'.

saschanaz avatar Aug 17 '14 10:08 saschanaz

Yea well, object literals are not the only problem:

interface A {
    default void foo() {
        console.log("A");
    }
}

interface B {
    default void foo() {
        console.log("B");
    }
}

class Bar implements A, B {
    default void foo() {    // required for conflict resolution
        console.log("Bar"); 
    }
}

var o = new Bar();
A o1 = o;
B o2 = o;
o.foo(); // Bar
o1.foo; // probably want A
o2.foo; // probably want B

From the client code perspective, default methods are just ordinary methods, so in case of the simple example with one class that implements an interface with a default method, prototype seems to be fine, however most of the time client code that invokes the default method will have to invoke the method at the call site. same old story. :zzz:

knazeri avatar Aug 17 '14 13:08 knazeri

For the record, here's an example of runtime exceptions in C#: http://stackoverflow.com/questions/5311465/extension-method-and-dynamic-object-in-c-sharp While TypeScript is certainly far more likely to have untyped variables than C# (I myself have about 60% variables untyped in my TS code and only about 10% untyped in C# code), this can be considered a known limitation. Maybe extension methods should only work with a "--noImplicitAny" compiler flag to decrease the possibility of a runtime error.

Personally I'm strongly against any silent prototype modifications - changes to any existing prototype (everything except initial class-defining code generated by TS compiler) should always be explicit, having programmer manually type "class.prototype" to prevent at least some part of the errors. Having said that, there's absolutely no reason to introduce new syntax for prototype extending: you can always do Square.prototype.getArea = /*...*/ and get all the syntactical benefits of such approach. If "rewriting call sites" is considered inappropriate, I think it's best to not introduce extension methods at all, than confuse programmers with a very dangerous silent prototype-changing feature.

Extension methods are nothing more than syntax sugar for method calls (at least that's how I see it and how they are implemented in C#). While certainly useful, they are not necessary.

zlumer avatar Aug 17 '14 21:08 zlumer

Hmm... this is my current suggestion:

class Square {
  width: number;
  height: number;
}

// I think this is explicit by itself, saying "This will extend Square.prototype".
extending Square {
  get area() {
    return this.width * this.height;
  }
}

// Let's make these two extending methods coexist.
function getArea() joins Square {
  // Extension functions can only access public properties, as normal functions works so.
  return this.width * this.height;
}

var square: Square;
var x: any = square;
square.area;
square<-getArea(); // New syntax to call extension functions
getArea(square); // Still allows normal function call
x<-getArea(); // Even works without any type information

becomes

var Square = (function () {
    function Square() {
    }
    return Square;
})();

(function () {
    Object.defineProperty(Square.prototype, "area", {
        get: function () {
            return this.width * this.height;
        },
        enumerable: true,
        configurable: true
    });
});

function getArea(_this) {
  return _this.width * _this.height
}

var square;
var x = square;
square.area;
getArea(square);
getArea(square);
getArea(x);

Edited: Added getArea(square);

saschanaz avatar Aug 18 '14 07:08 saschanaz

BTW, wouldn't 'conditional extension' help us? I think some extensions are to polyfill new standard functions for old browsers.

extending Window {
  // We don't want to overwrite functions that potentially already exist.
  createImageBitmap() { /* */ }
}

extending Window {
  // We cannot do this because this is already declared in lib.d.ts.
  setImmediate() { /* */ }
}

We would have to keep using Window.prototype.x = something, or window.x = something here, to add functions conditionally.

saschanaz avatar Aug 18 '14 15:08 saschanaz

So is this simply a syntax discussion? Since this can already be done this way:

module A {
  class B {
    c():void {}
  }

 // somewhere else.
 module B {
 // Extend.
  d():void {}
 }

}

electricessence avatar Aug 19 '14 18:08 electricessence

@electricessence That way you can add static members, not instance members (to the prototype).

@SaschaNaz I don't think we need a special syntax for that, because you don't need to add type-info for those functions. You can just write:

if (!window.setImmediate) {
    window.setImmediate = (cb: () => void) => window.setTimeout(cb, 1);
}

window.setImmediate(() => console.log(''));

ivogabe avatar Aug 19 '14 18:08 ivogabe

@ivogabe, That's right, but I would be happier if I can do that also with extension syntax, in the future when this is implemented anyway. Similar thing, similar syntax ;)

saschanaz avatar Aug 19 '14 19:08 saschanaz

Why not just use something like the kotlin syntax?

// some class A
class Hello {
    language: string;
}

extension Hello.printHello(name: string) {
    return "Hello, " + name + " in " + this.language;
}

danfma avatar Sep 10 '14 16:09 danfma

@danfma, :+1:

saschanaz avatar Sep 10 '14 18:09 saschanaz

If all you want to do is add an instance method why not just allow class declarations to merge and avoid the need for new syntax?

danquirk avatar Sep 10 '14 18:09 danquirk

@danquirk I guess the primary use case of extension methods is to make them work on interfaces

knazeri avatar Sep 10 '14 19:09 knazeri

Is this similar to a 'trait'?

class Shape {
 // ...
}

trait dimensions {
      getArea() { return /* ... */; }
}
Shape use dimensions;
Shape use {
      getArea() { return /* ... */; }
}

Or for compiled code:

class Shape2 extends Shape {
  use dimensions;
}

I don't know about 'use' as keyword, 'with' could be re-used:

Shape with dimensions;
Shape with {
      getArea() { return /* ... */; }
}

class Shape2 extends Shape {
  with dimensions;
}

jbondc avatar Sep 26 '14 19:09 jbondc

Would be nice if compiled time 'traits' and runtime 'extensions' can be baked into same concept: http://wiki.ecmascript.org/doku.php?id=strawman:trait_composition_for_classes

jbondc avatar Sep 26 '14 19:09 jbondc

To start you make it like C# and worry about syntax sugar later.

module A {
  class B {
    c():void {}
  }

 // somewhere else.
 module D {
 // Extend.
  static d(this target:B):void {}
 }

}

electricessence avatar Oct 28 '14 00:10 electricessence

@electricessence @danfma the problem lies mostly with compiler output, not syntax. You can see @RyanCavanaugh's great summary of two different approaches and their pros and cons.

zlumer avatar Oct 28 '14 07:10 zlumer