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
how are you querying for them? and do you have a pollyfill for Reflect.metadata?
added to the gist... Reflect.getMetadataKeys(House); this results empty array..
Yes, I'm requiring 'reflect-metadata' package
looks like the polyfill loosing it, @rbuckton can you take a look.
Think I got it... requires are moved after typescript's helper code
var __metadata = this.__metadata || (typeof Reflect === "object" && Reflect.metadata) || function () { };
require('reflect-metadata');
so, in time var __metadata is beeing inicialized, polyfill is not loaded yet
but i cannot get these requires before the generated code
EDIT: updated the gist.. when single module is compiled, there is no way to load polyfill before __metadata is resolved, because typescript's generated code is always moved to the top of the file
ooh.. this is a bigger issue. logged issue #2811 to track it
Until then you require reflect-metadata in another module (you need two files).
see https://github.com/matjaz/property-DI/
There appears to be an invocation inconsistency which makes developing decorators with variable/optional parameters pretty difficult to do. As an example:
@F
prop: number;
@F()
prop: number;
In the former, F gets invoked with the parameters (target, propertyName, propertyDescriptor) while in the latter, F gets invoked with the the parameters () and requires you have an internal function returned which in turn gets invoked with (target, propertyName and propertyDescriptor).
My assumption would have been that both @F and @F() would be equivalent and therefore you can only perform either call if the decorator supports 0 or more parameters.
This is particularly important in the case:
@F // Performs some default behaviour.
prop: number;
@F({ option: true }) // Performs some configured behaviour.
prop: number;
This can be worked around by just explicitly calling @F() instead of @F but it's easy to make that mistake and then be confused when your decorator doesn't work even though by the looks of it it should.
In this case I would like to do the following:
export function F(options?: any): PropertyDecorator {
return (target, name) => {
// do something.
}
}
and be done with it, but instead I have to do something like the following crude example:
export function F(...args: any[]): any {
var func = (target, name) => {
// do something.
}
if (args.length === 1) return func;
else if (args.length === 2) func(args[0], args[1]);
}
Which is a real pain.
@Tharaxis this behavior is by design. @F and @F() are not equivalent. @F calls a decorator F, where as @F() calls a decorator factor F with empty argument list, and then applies the resulting decorator.
The problem here is that the compiler compares the signature of the decorator factory F against declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; which ends up to be assignable. i think we need a stronger check here to make sure we catch these issue. I have logged #3246 to fix this. I believe you are doing the correct thing, and the compiler should catch invalid uses of a decorator factory.
@mhegazy I'm not sure why this is the case however, is there some use case that precludes one making @F and @F() equivalent, since ultimately they are both an identical invocation of the decorator function, just one of them happens to also include an invocation to an outer factory function? It seems like the principle of least astonishment is being violated here since this is definitely quite astonishing behaviour and I don't see why there have to be 2 ways to invoking a decorator from the perspective of the API consumer.
While I get that from a JS perspective there is a difference (in one you are passing the reference of the F function and the other you are executing a function and then passing in the reference of its result as the decorator), I'm not sure I understand why one cannot just have decorators that are passed as @F implicitly match (and invoke) the factory as one with an empty parameter list?
The compiler has no way to know if it is a factory or a decorator. if you have this signature:
declare function decoratorOrFactory (...args: any[]): any;
Is this a decorator or is it a factory, should it be called with empty arguments or not?
The most the compiler can do is verify that the signature matches when calling it one way or the other, and give errors if it does not.
@rbuckton has a fix for #3246 that should flag the cases where your decorator is not used as a factory, so stay tuned.
@mhegazy, what I'm saying is that the use of a decorator (i.e. @F or @F()) should always be an invocation of factory function F, which in turn returns the appropriate decorator type. There is no top-level representation of a decorator without an encapsulating factory.
In other words the signature of F is always:
declare function F(...args: any[]): ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator;
Or some equivalent.
Then invocation @F is made the equivalent of @F() by the compiler. Since both the signature of @F and @F() must match the factory signature in some form this solves the problem of invocation confusion. There is only one way to invoke a decorator!
Given the following:
declare function F(...args: any[]): PropertyDecorator {
return (target, name) => {
// do stuff.
}
}
@F()
property: number;
and
declare function F(target, name) { // Matches PropertyDecorator
// do stuff.
}
@F
property: number;
They do the same thing but I have to declare them differently! However, declaring F so that it can exist both ways is really cumbersome and makes creating consistent parameters and documentation impossible. You're either choosing that your decorator needs to use a factory or not, and your API consumer has to know this distinction before hand to make use of it.
@Tharaxis If I'm looking at a library providing F that will be used as a decorator, I absolutely expect @F and @F() to be different things. Just like I would expect C and C() to be different things - the first references a value, the second invokes a value. @F applies a decorator, @F() invokes a function that will create a decorator. Those are not, and should not be, the same operation.
@DavidSouther is there any valid reason why this cannot or should not be the case? There is no functional difference between an invocation of @F and @F() but there is a pretty big difference between how they are defined and documented, and it adds additional complexity to invocation that should be unnecessary.
My proposal is that there should be not be two ways to define a decorator because there is no need, and there should be no need to define a decorator more than one way.
There is no functional difference between an invocation of @F and @F()
I think this is the main point of contention. i do not think this is true. F is a reference to a function, F() is a reference to the return value of F when called with an empty argument set (i.e. F.call(this, [])); and these are two functionally, and conceptually different things.
@Tharaxis @F and @F() are different things. There is a difference in how they are used, a difference in how they are documented, and differences in their invocation that is absolutely necessary.
Let me ask it a different way: why must every decorator function be a factory? Using your proposal, it would be impossible to have a simple decorator.
@mhegazy while I will concede that the latter option (@F()) does result in the generation of a functional closure and additional overhead through the creation of isolated (and duplicated) decorator functions and the @F invocation essentially performs against a shared decorator function reference, I would say that the isolation through closure would be "safer" and more consistent, reducing the likelihood of surprises.
@DavidSouther Your question depends on what you define as a simple decorator. Nothing precludes one having a simple decorator in the form of:
declare function F(): PropertyDecorator {
return (target, name) => {
// do stuff
}
}
I find this pretty minimally invasive since it's only 2 lines more than the "simple syntax" and defines more obviously what the available decorator invocations are. Additionally, since there is then only a single way to define a decorator (and let us not discount the value of consistency), you'll probably take roughly another 2 seconds to whip this out compared to the "simple syntax".
Additionally a more problematic issue is as follows:
declare function F(options?: any): PropertyDecorator {
return (target, name) => {
// do stuff
}
}
@F()
property1: number;
@F
property2: number;
@F({ option: true })
property3: number;
One of these things is not like the other. The use of @F will not function even though at face value it definitely should. Keep in mind, pretend I am someone who is not aware of what the underlying declaration of F looks like, but instead just know that F exists and that it can take an optional set of arguments. The chances of me making a mistake with @F is not trivial under the current mechanism. This puts a large onus on the developer/documenter to make sure that the consumer is aware that @F will not work (but maybe @C will because it's "different" somehow).
If I want a "one size fits all" decorator, where the consumer doesn't have to worry, I have to do this ghastly thing:
declare function F(...args: any[]): any {
var decorator = (target, name) => {
// do stuff
}
// Heaven forbid your decorator formal parameter list also can take 2 parameters.
return (args.length === 2) ? decorator(args[0], args[1]) : decorator;
}
Which is quite frankly horrendous. Additionally, I lose all valuable parameter intellisense against decorator F since now it has to be generalised.
There is a lot to be said to having decorators be easy and consistent to define and document. Lets not fool ourselves into thinking that everyone consuming our code will have the same savvy or understanding as us who are the creators of that code.
@Tharaxis I thought about this early on in the design for decorators, and I understand your specific points. As @mhegazy and @DavidSouther mention previously in this thread, this behavior is consistent with the standard behavior of functions in JavaScript.
You are correct that any attempt to create a function that can act as both a decorator and a decorator factory can be somewhat complex. In general though, it may be better to employ a best practice to always use decorator factories, and supply rules to a linter to ensure this practice is adopted.
Also, I have just submitted PR #3249 to address your earlier point regarding inconsistencies in the type checking for decorators.
Hi @rbuckton,
I'm one of those not so savvy users of decorators mentioned by @Tharaxis...
I guess the question I would have is should decorators be consistent with functions? I.e. In the case of functions, returning this.f versus this.f() makes complete sense to me as sometime I want the value, sometimes I want the thing that produces the value.
In the case of decorators it doesn't seem quite as clear cut to me at the language feature level. I would like to argue that I just want to apply decorator @F, I don't really want to know whether it's been implemented as a factory or static method. That is unless I would loose some capability that decorators would otherwise have.
My apologies if the above is misinformed or ignorant, I'm relatively new the javascript world.
Thanks & cheers