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

@mikeaustin I like it, that's a very clean emit, I'm curious to see how your language progresses.

With respect to type directed in async methods, IIRC it only rears its ugly head when you don't use type inference for return types and don't install a global Promise polyfill, as it only considers the type when provided, defaulting back to the global Promise.

I couldn't care less about the extra methods available on Bluebird Promises and I never specify the return type of async methods.

So I believe the issue is easily dodged, but I may be wrong and it may be affecting me in some other way that I'm not aware of.

aluanhaddad avatar Apr 07 '17 21:04 aluanhaddad

Sorry for spamming the TypeScript list, but I made a slight change in my extension methods to support traits/mixins that might be interesting. When extension methods were in local scope, there was no good way (aka not using eval()) to dynamically add methods.

So, I encapsulated them in a _methods lexically scoped object:

var Iterable = new Trait({
  // iterator() can be an extension method or a plain old function
  map: (iterator) => (func) => { var iter = iterator.apply(this); ... }
});

var _methods = Extension.extend(_methods, String, {
  iterator: () => { return new Iterator(this); }
});

// Bind all the trait methods and pass them to extend String
var _methods = Extension.extend(_methods, String, Iterable.bind(_methods.iterator));

_methods.map.apply("abc", [c => c.charCodeAt(0)]); // [97, 98, 99]

I can probably simplify extend() a bit more. The language this is targetting: Impulse-JS.

mikeaustin avatar Apr 19 '17 23:04 mikeaustin

With the amount of library authoring going on and what seems like increased adoption of TS, now seems like a great time to dust this idea off and see if it's worth dedicating resources to!

Again, biggest thing is for libraries. I already find myself very badly wishing for some kind of idiomatic way to sprinkle some extensions around.

✏️

atrauzzi avatar May 10 '17 01:05 atrauzzi

Seems people aren't reading the thread.

RyanCavanaugh avatar May 10 '17 17:05 RyanCavanaugh

I would personally be happy if Typescript had extension methods that used a distinct call syntax vs. normal method invocations.

For instance:

function Date#toProto(): Timestamp { ... }

function usage() {
  const proto: Timestamp = new Date()#toProto(); // instead of toDateProto(new Date())
}

This would allow

  1. call chaining and fluent usage of extension functions. You can write foo.toBar().toBaz() instead of barToBaz(fooToBar(foo)).
  2. easy discovery of extension functions through IDE autocomplete. new Date()# or new Date(). would show toProto() in the autocomplete list; selecting that item could auto import the extension function. Such functions might be more easily discoverable compared to toDateProto().

I suspect it would avoid some of the complications from https://github.com/microsoft/TypeScript/issues/9#issuecomment-74302592. Making extension functions callable from JavaScript might require some attention, however.

reddaly avatar Jul 15 '24 17:07 reddaly

@reddaly out of scope for TypeScript. See https://github.com/tc39/proposal-bind-operator though

RyanCavanaugh avatar Jul 15 '24 17:07 RyanCavanaugh

What makes the https://github.com/microsoft/TypeScript/issues/9#issuecomment-2229040453 suggestion out of scope for TypeScript?

Extension methods seem like they should be resolved at compile-time based on typing information that's out of scope for ECMAScript. I'm not sure how ECMAScript could possibly provide the same level of utility through the bind operator.

function Foo::toProto(): FooProto { ... }
function Bar::toProto(): BarProto { ... }

(new Foo())::toProto() // resolves to first method
(new Bar())::toProto() // resolves to second method

edit:

Reading into https://github.com/tc39/proposal-bind-operator, it seems the "::" would help a lot. However, in the above example, multiple "toProto" methods probably could not be imported into the same TypeScript file - they would have to be aliased.

import {toProto as toFooProto } from './foo-extensions'
import {toProto as toBarProto } from './foo-extensions'

(new Foo())::toFooProto()
(new Bar())::toBarProto()

This might seem like a small detail, but the namespacing provided by a method receiver is helpful for keeping method names concise.

gonzojive avatar Jul 26 '24 03:07 gonzojive

Extension methods seem like they should be resolved at compile-time based on typing information

That's type-directed emit. See https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals point 4:

[Do not] Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.

RyanCavanaugh avatar Jul 26 '24 17:07 RyanCavanaugh

Thanks. It seems the more active proposal is https://github.com/tc39/proposal-extensions. I asked here about the status of that proposal advancing to stage 2. Presumably TypeScript is not interested in introducing its own bind operator before there is consensus to add the operator to JavaScript.

gonzojive avatar Jul 27 '24 18:07 gonzojive

Hi,

I'd really appreciate some guidance. I was playing around with ast transformers to see if I could have a custom extension method implementation (here: https://github.com/codibre/extension-methods/pull/3). I achieve making something like that work:

The extension declaration:

import { ExtensionMethod } from 'extension-method';

export class ExtensionTest {
    @ExtensionMethod
    static myTest(str: string) {
        return 123;
    }
}

declare global {
  interface String {
    myTest(): number;
  }
}

Where it is used:

import './extension';

console.log("abc".myTest());

In the test I'm running, it compiles to something like this:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const extension_1 = __importDefault(require("./extension"));
console.log(extension_1.ExtensionTest.myTest("abc"));

Which nails the idea, although there are many scenarios I need to explore. The issue with this solution, though, is that the extension declared to String here is visible regardless of whether I've imported the extension file. Can I write the "type augmentation" somehow so the extension method will only be visible when I import the file where it is declared?

I see that the extension will only work if I import the extension file, which is ideal for the concept. However, if I could somehow have some "scoped argumentation" for existing types, I'd be able to reflect this behavior also in typescript, but I'm unaware of such a feature.

Farenheith avatar Jan 20 '25 03:01 Farenheith