TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Decorators

Open rbuckton opened this issue 11 years ago • 139 comments

ES7 proposal

The ES7 proposal for decorators can be found here: https://github.com/wycats/javascript-decorators The ES7 proposal serves as the base of this proposal. Below are notes about how the type system

Decorator targets:

Class constructor

@F("color")
@G
class Foo {
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo = __decorate([F("color"), G], Foo);
    return Foo;
})();

Methods

class Foo {
  @F(color)
  @G
  bar() { }
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.bar = function () {
    };
    Object.defineProperty(Foo.prototype, "bar", __decorate([F(color), G], Foo.prototype, "bar", Object.getOwnPropertyDescriptor(Foo.prototype, "bar")));
    return Foo;
})();

Static method

class Foo {
    @F("color")
    @G
    static sMethod() {}
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.sMethod = function () {
    };
    Object.defineProperty(Foo, "sMethod", __decorate([F("color"), G], Foo, "sMethod", Object.getOwnPropertyDescriptor(Foo, "sMethod")));
    return Foo;
})();

Properties

class Foo {
    @F("color")
    @G
    prop: number;
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    __decorate([F("color"), G], Foo.prototype, "prop");
    return Foo;
})();

Method/Accessor formal parameter

class Foo {
    method(@G a, @F("color") b) {}
}

desugars to:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.method = function (a, b) {
    };
    __decorate([G], Foo.prototype, "method", 0);
    __decorate([F("color")], Foo.prototype, "method", 1);
    return Foo;
})();

Where the __decorate is defined as:

var __decorate = this.__decorate || function (decorators, target, key, value) {
    var kind = typeof (arguments.length == 2 ? value = target : value);
    for (var i = decorators.length - 1; i >= 0; --i) {
        var decorator = decorators[i];
        switch (kind) {
            case "function": value = decorator(value) || value; break;
            case "number": decorator(target, key, value); break;
            case "undefined": decorator(target, key); break;
            case "object": value = decorator(target, key, value) || value; break;
        }
    }
    return value;
};

Decorator signatures:

A valid decorator should be:

  1. Assignable to one of the Decorator types (ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator) as described below.
  2. Return a value (in the case of class decorators and method decorator) that is assignable to the decorated value.
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;

Notes:

  • Decorating a function declaration is not allowed as it will block hoisting the function to the top of the scope, which is a significant change in semantics.
  • Decorating function expressions and arrow functions are not supported. The same effect can be achived by applying the decorator function as var x = dec(function () { });
  • Decorating function formal parameters is currently not part of the ES7 proposal.
  • Decorators are not allowed when targeting ES3

rbuckton avatar Mar 07 '15 03:03 rbuckton

@sccolbert You might do better for that with ES6 proxies rather than property decorators.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

DavidSouther avatar Sep 04 '15 13:09 DavidSouther

@DavidSouther browsers don't support Proxies yet :(

sccolbert avatar Sep 04 '15 13:09 sccolbert

@cybrown Yes, it uses the property descriptor for methods and accessors. I tested on plain properties (fields w/o accessors) only. But it seems that decorators can be allowed in ES3 for properties (w/o accessors) and classes. It would be helpful.

Koloto avatar Sep 04 '15 13:09 Koloto

And a fake property descriptor can be used for methods when targeting ES3. Something like { writable: true, enumerable: true, configurable: true }. So I can't see any reason to not support ES3.

Koloto avatar Sep 04 '15 13:09 Koloto

@sccolbert I see. That makes sense. Incidentally, TypeScript is working on improved this typing for functions and methods. I wonder if that would be of any help here. Although I suppose typing is not the issue for you, it's runtime semantics.

JsonFreeman avatar Sep 05 '15 03:09 JsonFreeman

@JsonFreeman Improved this typing sounds intriguing for some of my other use cases. Do you have any more info on that?

sccolbert avatar Sep 05 '15 03:09 sccolbert

I think the most developed discussion on this typing is at #3694.

JsonFreeman avatar Sep 05 '15 04:09 JsonFreeman

Cheers!

sccolbert avatar Sep 05 '15 04:09 sccolbert

error TS1207: Decorators cannot be applied to multiple get/set accessors of the same name.

@get
public get myValue():any{...}

@set
public set myValue(value:any){...}

code above is not allowed even it make more sense compare to

@get
@set
public get myValue():any{...}

public set myValue(value:any){...}

TakoLittle avatar Sep 19 '15 16:09 TakoLittle

Getter and setter are defined in one call to Obect.defineProperty. This rather a js quirk, the declaration of set and get though separate, really are the same property declaration. The error check in the compiler is to alert users when thinking of them separately; the decorators are applied only once to the property descriptor.

mhegazy avatar Sep 19 '15 21:09 mhegazy

just wondering since the compiler can sense the get and set with same name and combine into single Object.defineProperty, why not also combine the decorator? or perhaps an option flag to tell compiler to combine them, and leave a warning message instead of throwing error.

thank you

TakoLittle avatar Sep 21 '15 02:09 TakoLittle

@TakoLittle: The reason we don't do this today partially stems from how decorators are composed. Decorators follow the same principals as Mathematical function composition, where (f ∘ g)(x) is composed as f(g(x)). In the same sense, it can be thought that:

@F
@G
class X {}

Is approximately:

F(G(X))

The compositionality of decorators breaks down when you decorate both the getter and the setter:

class C {
  @F
  set X(value) {}

  @G
  get X() {}
}

How do F and G compose here? Is it based purely on document order (i.e. F(G(X)))? Are each set of decorators for the getter and the setter discrete, and then executed in document order (i.e. G(F(X)))? Do get and set imply any specific ordering (i.e. is the get always before the set or vice versa)? Until we're 100% certain the most consistent approach that doesn't surprise users, or have a well documented approach that is part of the decorators proposal with at least stage 2 or better acceptance within ECMA-262, we feel it is best to be more restrictive and error here as it allows us to relax that restriction at a later date without introducing a breaking change that could easily go unnoticed and possibly result in unexpected behaviors at runtime.

rbuckton avatar Sep 21 '15 04:09 rbuckton

@rbuckton thank you so much for detailed explanation TS team great work!! ^^d

TakoLittle avatar Sep 21 '15 08:09 TakoLittle

Where is the documentation for this? and care to link the implementation commit?

Thanks.

omeid avatar Feb 20 '16 06:02 omeid

@mhegazy What is the status on the implementation of the latest version of the spec. I understand there are some changes there.

EisenbergEffect avatar Feb 20 '16 17:02 EisenbergEffect

This issue tracked the original version of the proposal. since this is completed we are closing this issue. for any updates to the spec, we will log new issues and outline all the breaking changes. I do not think the proposal is at a place now to be ready for us to jump on it. We are working closely with @wycats on the new proposal.

mhegazy avatar Feb 22 '16 23:02 mhegazy

@omeid, you can find documentation at https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Decorators.md

mhegazy avatar Feb 22 '16 23:02 mhegazy

@mhegazy Thank you for the update. I'd love to stay informed. When you create the new issue for the spec update, please link it here so I can be notified and follow. The Aurelia community makes heavy use of decorators and we'll want to synchronize with both TypeScript and Babel on the update. Again, thanks for the great work the TS team is doing!

EisenbergEffect avatar Feb 23 '16 21:02 EisenbergEffect

Function decoration is need of course. Are there also plans for decorating of other objects in the code?

wclr avatar Aug 27 '16 20:08 wclr