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

+1 I think the extension methods should support interfaces and be a syntactical sugar like in C#:

interface IMovable {
    position: Point;
}
extension class MyExtensions {
    move(this moveable: IMovable, newPoint: Point) {
...
    }
}
var car: Movable = {...};
car.move(newPoint);

this will compile to:

var MyExtensions = {
      move...
}
var car = {...};
MyExtensions.move(car, newPoint);

ronzeidman avatar Dec 19 '15 10:12 ronzeidman

if this isn't already the case i think @ronzeidman is absolutely right :+1:

TrabacchinLuigi avatar Jan 22 '16 09:01 TrabacchinLuigi

If we are really hesitant to support extension class Homu syntax, can we just add type information from Homu.prototype.method1 = () => {}, similar to what Salsa does (#4955)?

saschanaz avatar Jan 22 '16 10:01 saschanaz

@ronzeidman @TrabacchinLuigi you need to read https://github.com/Microsoft/TypeScript/issues/9#issuecomment-74302592

RyanCavanaugh avatar Jan 22 '16 22:01 RyanCavanaugh

@RyanCavanaugh The example in https://github.com/Microsoft/TypeScript/issues/9#issuecomment-74302592 is a good one. I've now read the entire thread and there were great suggestions, I like the ES7 bind operator (::) but I suggest something a bit different - introducing an "Elixir" like pipe operator "|>":

function getArea(x: Rectangle) { ... }

var myRectangle = new Rectangle();
myRectangle |> getArea();

it will make things like "extending" array functions much easier and much more readable without changing the prototype:

grouppedReduce(groupBy(mySort(myArray.map(...), ...).filter(...), ...), ...);
myArray.map(...)|>mySort(...).filter(...)|>groupBy(...)|>grouppedReduce(...);

What do you say?

ronzeidman avatar Jan 23 '16 07:01 ronzeidman

We're almost certainly not taking up any new runtime operators that don't have at least some traction with the ES committee (especially when there are competing operators with similar meaning), so taking that to ESDiscuss would be the next step if you'd like to see it happen.

RyanCavanaugh avatar Jan 25 '16 05:01 RyanCavanaugh

@RyanCavanaugh I like the bind operator too!

TrabacchinLuigi avatar Jan 25 '16 09:01 TrabacchinLuigi

@RyanCavanaugh I agree, and the bind operator (of which I guess people agree on since its an ES7 suggestion) could work really well, especially if you could configure the type of "this" the function can get like in https://github.com/Microsoft/TypeScript/issues/6018 suggestion

ronzeidman avatar Jan 25 '16 16:01 ronzeidman

Hey just want to express my +1 for @ronzeidman -style extension classes with a few more words. I fully realize that this is something that will differentiate TS from ES, since it's impossible to pull it off without a type system, but I also think that this is the sort of thing that leverages the type system for an amazing gain in developer experience, and it makes perfect sense for our language.

ES will obviously never get a type system which means it will never be able to get this feature either, while we can easily have and love it every day. It transpiles to ok looking JS, and to anyone thinking otherwise, well today I have to type a lot of the same stuff manually on a daily basis. Re: worries that methods won't behave as usual when deferenced or tested for existence, etc, I really don't see this a major problem, since that is rather niche usage wrt method calling. As such those can result in a compiler error and I just don't see how that can become a problem.

Aside from the obvious case for interfaces, it'd allow one to extend collection types like MyType[] that just cannot be done otherwise sensibly. Underscore-like utility libraries will become a syntactic bliss. I imagine it'll play very nicely with this-typing for building fluent apis too.

Brief - life will be greater, and more beautiful, and so much more fantastic! We have a type system, there's nothing wrong in using it to make our lives even better. This feature relies entirely on the type system, and as such, in my opinion, is a perfect fit for TS.

hdachev avatar Jan 26 '16 17:01 hdachev

I believe the Extensions implemented in Swift 2.1 is a very good example of how it could be implemented (as initial proposal at least)

Will allow us to do something like the following example here

gabrielPeart avatar Mar 17 '16 12:03 gabrielPeart

Class extension would be useful for separated definition members with different access level:

class A {}

private extension class A {
    func1() : void =>  {}
}

protected extension class A {
    func2() : void =>  {}
}

ghost avatar May 13 '16 22:05 ghost

Just wanted to give my humble suggestion, pardon my two-week TypeScript skills.

I have been reading this discussion and maybe we are trying to do something primarily designed for type-based systems. JavaScript is much less typey, so work with that (this syntax is just one way):

Given this class:

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

Case 1: Does not touch the prototype:

extension class SimpleSquareExtensions<Square> {
    depth: number = 0;
    static scale: number = 0;

    // must be static
    static function getArea(this square: Square) {
        // Can't access `depth` at all, not static
        // Can't do this: `square.scale` - not on Square
        // Can do this: `SimpleSquareExtensions.scale`
        return square.width * square.height;
    }
}

// JS:
SimpleSquareExtensions.scale = 0;
SimpleSquareExtensions.prototype.depth = 0;
SimpleSquareExtensions.getArea = function (square) {
    return square.width * square.height;
}

This is a very basic type that does not touch the Square prototype, so:

var sq: Square = new Square();

var area = sq.getArea();
// JS:
// var area = SimpleSquareExtensions.getArea(sq);

var anySq: any = sq;
var anyArea = anySq.getArea(); // No Intellisense for getArea()
// JS:
// var anyArea = anySq.getArea();
// Runtime error - expected

This works like C# dynamic object, I can't apply a Square extension method to an object that might not be a square.

Also, we could, or not, permit other non-extension members on the class, such as the depth and scale properties. (could be methods too)

Case 2: Adds to the prototype:

extension class MoreSquareExtensions<Square> {
    extension static scale: number = 0;
    extension depth: number = 0;

    extension static function getArea(this square: Square) {
        // Can't do this: `square.depth` - static method
        // Can't do this: `Square.depth` - not static field
        // Can't do this: `MoreSquareExtensions.depth` - not on MoreSquareExtensions
        // Can't do this: `square.scale` - static field
        // Can't do this: `MoreSquareExtensions.scale` - not on MoreSquareExtensions
        // Can do this: `Square.scale`
        return square.width * square.height;
    }

    // no need for static
    extension function getVolume(this square: Square) {   
        // Can't do this: `Square.depth` - not static field
        // Can't do this: `MoreSquareExtensions.depth` - not on MoreSquareExtensions
        // Can't do this: `square.scale` - static field
        // Can't do this: `MoreSquareExtensions.scale` - not on MoreSquareExtensions
        // Can do this: `square.depth`
        // Can do this: `Square.scale`             
        return square.width * square.height * square.depth;
    }
}

// JS:
Square.scale = 0;
Square.prototype.depth = 0;
Square.getArea = function (square) {
    return square.width * square.height;
}
Square.prototype.getVolume = function () {
    return this.width * this.height * this.depth;
}

Due to the extension keyword, the developer is instructing the compiler to modify the type. The dev is responsible for resolving conflicts:

var sq: Square = new Square();

var area = sq.getArea();
// JS:
// var area = Square.getArea(sq);

var anySq: any = sq;
var anyArea = anySq.getArea(); // Still no Intellisense?
// JS:
// var anySq = sq;
// var anyArea = anySq.getArea();
// works as expected, because it is on the prototype

sq.depth = 10;
var volume = sq.getVolume();
// JS:
// sq.depth = 10;
// var volume = sq.getVolume();

Basically, what I am trying to do is sort of follow what the dynamic keyword would do in C#, but also permit the explicit extension of an existing prototype like JavaScript.

I am still not too sure what the best is for the class declaration:

extension class MyExtensions<Square> { }
class MyExtensions extensionof Square { }
extension class MyExtensions extension Square { }

might be best to avoid the instantiation of MyExtensions... C# required that the class and method be static, and the method have the this. But, JavaScript does allow the extension if instance members, so static can't be a requirement. Maybe we could say that if the method was explicitly marked as extension, then the first this parameter can be removed and you can use the this keyword in the method body itself. This way the extension fields and existing fields can work the same?

mattleibow avatar Jun 11 '16 18:06 mattleibow

Case 1 would be the best thing since sliced bread because it'll work with interfaces, generics, builtins and third party types extremely well. It's an extremely modular feature, and will work automatically with future extensions of the type system.

Case 2 only works for extending classes, can't work on interfaces, can't work on builtins without polluting them, and can't work only on select generic type parametrizations.

For example - in Case 1 - when imported, your getArea method will be available on an HTMLCanvas element, because it has width and height properties. How awesome is that?

On Saturday, 11 June 2016, Matthew Leibowitz [email protected] wrote:

Just wanted to give my humble suggestion, pardon my two-week TypeScript skills.

I have been reading this discussion and maybe we are trying to do something primarily designed for type-based systems. JavaScript is much less typey, so work with that (this syntax is just one way):

Given this class:

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

Case 1: Does not touch the prototype:

extension class SimpleSquareExtensions { depth: number = 0; static scale: number = 0;

// must be static
static function getArea(this square: Square) {
    // Can't access `depth` at all, not static
    // Can't do this: `square.scale` - not on Square
    // Can do this: `SimpleSquareExtensions.scale`
    return square.width * square.height;
}

}

// JS: SimpleSquareExtensions.scale = 0; SimpleSquareExtensions.prototype.depth = 0; SimpleSquareExtensions.getArea = function (square) { return square.width * square.height; }

This is a very basic type that does not touch the Square prototype, so:

var sq: Square = new Square();

var area = sq.getArea(); // JS: // var area = SimpleSquareExtensions.getArea(sq);

var anySq: any = sq; var anyArea = anySq.getArea(); // No Intellisense for getArea() // JS: // var anyArea = anySq.getArea(); // Runtime error - expected

This works like C# dynamic object, I can't apply a Square extension method to an object that might not be a square.

Also, we could, or not, permit other non-extension members on the class, such as the depth and scale properties. (could be methods too)

Case 2: Adds to the prototype:

extension class MoreSquareExtensions { extension static scale: number = 0; extension depth: number = 0;

extension static function getArea(this square: Square) {
    // Can't do this: `square.depth` - static method
    // Can't do this: `Square.depth` - not static field
    // Can't do this: `MoreSquareExtensions.depth` - not on MoreSquareExtensions
    // Can't do this: `square.scale` - static field
    // Can't do this: `MoreSquareExtensions.scale` - not on MoreSquareExtensions
    // Can do this: `Square.scale`
    return square.width * square.height;
}

// no need for static
extension function getVolume(this square: Square) {
    // Can't do this: `Square.depth` - not static field
    // Can't do this: `MoreSquareExtensions.depth` - not on MoreSquareExtensions
    // Can't do this: `square.scale` - static field
    // Can't do this: `MoreSquareExtensions.scale` - not on MoreSquareExtensions
    // Can do this: `square.depth`
    // Can do this: `Square.scale`
    return square.width * square.height * square.depth;
}

}

// JS: Square.scale = 0; Square.prototype.depth = 0; Square.getArea = function (square) { return square.width * square.height; } Square.prototype.getVolume = function () { return this.width * this.height * this.depth; }

Due to the extension keyword, the developer is instructing the compiler to modify the type. The dev is responsible for resolving conflicts:

var sq: Square = new Square();

var area = sq.getArea(); // JS: // var area = Square.getArea(sq);

var anySq: any = sq; var anyArea = anySq.getArea(); // Still no Intellisense? // JS: // var anySq = sq; // var anyArea = anySq.getArea(); // works as expected, because it is on the prototype

sq.depth = 10; var volume = sq.getVolume(); // JS: // sq.depth = 10; // var volume = sq.getVolume();

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/9#issuecomment-225385496, or mute the thread https://github.com/notifications/unsubscribe/AASm69pd5PdoRiuIuBf1_-E7L560SIVDks5qKwScgaJpZM4CNZ1k .

hdachev avatar Jun 12 '16 10:06 hdachev

@mattleibow seems like you're proposing partial classes, see #563

RyanCavanaugh avatar Jun 13 '16 17:06 RyanCavanaugh

can we extension interface? interface can also have some implemented functions, just like Swift:

interface Rect {
    x: number
    y: number
}

extension Rect {
    area() => this.x * this.y
}

Swift version:


protocol Rect {
    var x: Float {get}
    var y: Float {get}
}
extension Rect {
    func area() -> Float {
        return self.x * self.y
    }
}

frogcjn avatar Jul 03 '16 18:07 frogcjn

can we extension interface?

It can be dangerous: https://github.com/Microsoft/TypeScript/issues/9#issuecomment-52329918, https://github.com/Microsoft/TypeScript/issues/9#issuecomment-52347966

saschanaz avatar Jul 03 '16 18:07 saschanaz

@SaschaNaz I don't think so. Swift already deal with it. It just add a prototype function to every class which implements it.

There is many detail works done by Swift team in Swift to solve the worry about the different package issue.

frogcjn avatar Jul 03 '16 18:07 frogcjn

@SaschaNaz I think interface extension is no more dangerous than class extension.

The way to solve the conflicting problem is using developer‘s import to decides which implementation should use. And also when package author extends some global interface or properties, they always use perfix to identify the extension. For example, RxSwift package extends UIView class with rx_dellocated. When developer import "RxSwift", the UIView will have rx_deallocated property. If developer don't import "RxSwift", there is no rx_deallocated with UIView.

frogcjn avatar Jul 03 '16 19:07 frogcjn

Given the constraints imposed by emit (see https://github.com/Microsoft/TypeScript/issues/9#issuecomment-74302592), there are realistically only two paths forward for object-first non-property method invocations:

  • Partial classes (#563)
  • ES20xx 'bind' operator (#3508)

I think we're reasonably satisfied (minus bikeshedding) on partial classes, and these can already be emulated today with a not-distasteful syntax (elucidated here: https://github.com/Microsoft/TypeScript/issues/563#issuecomment-218016147). I'd encourage anyone to weigh in meaningfully on extension vs partial vs other keywords, keeping in mind that we didn't just say "yea partial sounds good" and be done with it.

The ES20xx 'bind' operator ('xx' because who knows what version) is still in semantic flux and we need that proposal to either die cleanly (to let us lay clear claim to that syntactic space), or proceed with clear semantics, before we can act on it. It's an area where TypeScript can't safely act unilaterally. There's good discussion going on at https://github.com/tc39/proposal-bind-operator/issues/24 and its parent repo that outlines next steps for the proposal and it'd be great for people to perform citizen advocacy at ESDiscuss or other forums to help this move forward.

RyanCavanaugh avatar Jul 31 '16 22:07 RyanCavanaugh

I'm not sure if this has been suggested yet (this is a long thread), but what about compiler warning or compiler errors with explicit override (like eslint "ignore this" comments) for call site replacement?

That is in the situation implied in this comment , instead of silently failing in the second example an error is emitted akin to "extension method called on unknown type" and the following code can be used to remove the error:

process(((n) => {
    n.getArea(); //@compiler:no extension
}));

I haven't seen this type of explicit compiler hints in typescript, and perhaps it's intentional, but I think that call site replacement is a very powerful tool that a majority of developers would love to use, and the situation described in the comment will almost never happen. I don't think Typescript should fall into undefined behaviour at runtime, but I think that an error and an explicit optout will prevent anyone from unwittingly making this mistake.

alonbardavid avatar Aug 01 '16 07:08 alonbardavid