Decorators
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:
- Assignable to one of the Decorator types (ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator) as described below.
- 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
Excuse me from what I understand of the spec, we won't be able to do:
@F
function test() {
}
Am I right ?
How does type serialization work with rest arguments?
@F()
class Foo {
constructor(...args: string[]) {
}
}
function F(@paramterTypes types?: Function[]) {
return function (target) {
target.paramterTypes = types; // ???
}
}
Using decorators seems straightforward enough, but I found the sections about declaring them to be confusing. C.4 says decorators need to be annotated with @decorator, but not a single one of the examples actually shows this happening.
Are decorator factories intended to be classes that implement the interfaces found in B?
What is the rule for refining the interpretation of CoverMemberExpressionSquareBracketsAndComputedPropertyName?
I noticed many of the typings have Function | Object at various points, but these will degenerate to Object at type check time. What is the reason to have Function there?
I am not crazy about the terms DecoratorFunction vs DecoratorFactory. I'd much rather follow the nomenclature of generators, which has Generator and GeneratorFunction. With this scheme, we would rename DecoratorFunction to Decorator, and DecoratorFactory to DecoratorFunction.
For the decorated exports, what is [lookahead ≠ @] for? Can HoistableDeclaration and ClassDeclaration actually start with a @?
This is a dup of #1557
It's not really a dupe, as #1557 was for a different design. This issue is for the decorators design being implemented now.
My mistake.
For decorator on function expression, could we not do something like :
@F("color") @G
function myFunc() {
doSomething();
}
transformed in :
var _t = function() {
doSomething();
}
_t = F("color")(_t = G(_t) || _t) || _t;
function myFunc() {
return _t.apply(this, arguments)
}
It's a bit bother some to have to right every function like :
const myFunc = function () {}
You loose hoisting, and function.name
Implementation added in PR #2399
Updates: Proposal updated, and added link to the @wycats ES7 JavaScript decorators.
saddened that it became a class only thing ... Also what about ambiant decorator did they get out of the scope ?
@fdecampredon with your proposal for functions, seems like you still lose the hoisting.
@JsonFreeman why ? if you insert _t at the top of the file ?
import something from 'something';
myFunc(something.something());
@F("color") @G
function myFunc() {
doSomething()
}
import something from 'something';
var _t = function() {
doSomething();
}
_t = F("color")(_t = G(_t) || _t) || _t;
myFunc(something.something());
function myFunc() {
return _t.apply(this, arguments)
}
Also even if my proposal has a lot of issues, I would seriously like to be able to use decorators on function (even if I have to use variable assigned function) and lose hoisting. Case like this gist seems a pretty good decorator use case for both function and class (especially coupled with ambient decorators if they still end up being in the scope)
@fdecampredon this does not work for the general case, as the decorators are expressions themselves. e.g.
myFunc(); // assumes function declaration is hoisted
var dec = (t) => t; // defininig a decorator
@dec
function myFunc() {}
if you hoist the function declaration and application of the decorator then you break the decorator. if you only hoist the function declaration, but not the decorator application you can witness the function in an undecorated state. no appealing solutions here.
this is the same issue as with class declaration extend clause, which in ES6 is an expression. the result was not hoisting the class declaration, just the symbol (akin to var declaration, but not function declarations)
Oups didn't think about it thank you @mhegazy. However why the function part have completely abandoned the original @jonathandturner proposal had the rule :
decorated function declarations cannot be hoisted to the containing scope
Loosing hoisting is sure a drawback, but I find it damageable to transform it into an class only feature when it would have use case for other construct.
Let's see what the desired set of constraints seem to imply:
- decorated function should be hoisted
- function should be decorated as soon as it is available - therefore decorator application must be hoisted
- decorator must be defined before it is applied - therefore decorator definition itself (or all entities referenced by the decorator expression) must be hoisted
- decorator expression gets evaluated at the place it is lexically applied - therefore the application cannot be hoisted
The only resolution I can see for this is the following: For function decorators, we only allow something of the form @identifier. We do not allow a left hand side expression. In addition, the identifier must be a direct reference to a function declaration (including a decorated function). All function decorations that take place in the scope must be emitted at the top of the scope, in the order that they were applied.
The problem breaking hoisting rules is that it is surprising. If you are writing javascript for a while you expect function declarations to be available before they are lexically declared; now by adding a seemingly simple syntactic marker (the decorator) this fundamental nature of function declaration is altered.
Having said that, the ES7 proposal is still in its initial stages, so I expect it to evolve and expand; so it is conceivable that the final proposal would include functions in some form.