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
I do think they should be hoisted. I am saying that the only decorations we allow on functions are decorations that are definitely themselves hoisted. Namely identifiers that reference function declarations.
But there is another problem here. It is actually impossible to simultaneously hoist all decorated functions and ensure that they are not observed in their undecorated state. The problem can be seen with a decorator cycle.
@dec1
function dec2(target: Function) {
// Do stuff
}
@dec2
function dec1(target: Function) {
// Do stuff
}
Even if both functions are hoisted, which one gets decorated first? If dec2 gets decorated first, then dec1 will not itself be decorated by the time it is applied to dec2.
So we would have to choose between the following:
- The functions are not hoisted
- The undecorated functions are hoisted, but the decorator applications don't get hoisted with them.
While I don't like either of these, I don't even think anything else is possible.
This is the JS proposal. so the engine would not know if the expression refers to a function declaration or not, with static analysis we could tell though. consider this:
@dec1
function dec2(target: Function) {
// Do stuff
}
dec2 = undefined;
@dec2
function dec1(target: Function) {
// Do stuff
}
Ugh! Javascript not getting any simplier anymore. :-)
It would be easier to enable it only on function expressions:
const foo = @decorator () => {
// ...
}
const bar = @decorator function() {
// ...
}
Function expressions or lambda's aren't hoisted.
Is it possible to have parameters like this in a decorator in typescript 1.5.0-alpha ?
@dec1({key1: value1, key2, value2})
function dec2(target: Function) {
// Do stuff
}
Ok nevermind, just create a factory which takes the parameters and return the actual decorator function.
For example, a class decorator with a string parameter:
function decoratorWithString(param: string) { // Decorator factory
return function(target) { // Actual decorator
// Do stuff with target and string parameter
}
}
// Usage
@decoratorWithString('foobar')
class Foo {
}
greetings.
i am trying to figure out how to write a decorator that will pick up the types declared in the constructor.
here's some code that illustrates what i'm trying to do, but it is hardwired. i need it to respond to the constructor declaration in class D
class A {
public message = "identity: class A";
}
class B {
public message = "identity: class B";
}
@decoTest
class D {
static metadata:Array<Function> = [];
constructor(a: A, b: B) {
}
}
describe("decorators", function() {
it("should inject constructor types", function() {
var d = new D(new A(), new B());
expect(D.metadata.length).toBe(2);
});
});
function decoTest<T>(target: T, ...rest) {
target["metadata"].push(A, B); // how do i get this based on constructor ???
return target;
}
I am afraid that type information is out of scope of the decorator feature. You can use ParameterDecorator on each parameter to add that kind of information.
The typing or implementation for ParameterDecorator is not quite correct, from the typings the target is a function, but while using typescript, it is the prototype object. I must cast the target parameter in order to get the right type:
function MyParameterDecorator (_target: Function, methodName: string, index: number) {
const target = <InterfaceForMyUseCase><anyt>_target;
// do stuff
}
Instead of:
function MyParameterDecorator (target: InterfaceForMyUseCase, methodName: string, index: number) {
// do stuff
}
wow - parameter decorators rule !!!!!!!!!!!!!!! see this repo
here's the output from running the tests:
LOG: 'injectMe:'
LOG: ' type: class A'
LOG: ' type: class B'
LOG: ' some key'
and the code:
module ParameterDecorators {
class A {
static typeName:string = "type: class A";
public instanceTypeName = "instance: class A";
}
class B {
static typeName:string = "type: class B";
public instanceTypeName = "instance: class B";
}
@injectTest(A, B, "some key")
class C {
static injectMe: Array<any> = [];
constructor(a: A, b: B) {
}
}
function injectTest(...rest) {
return function(target): void {
target["injectMe"] = rest;
}
}
describe("decorators", function() {
it("should inject dependency-injection keys", function() {
var c = new C(new A(), new B());
console.log("injectMe:");
for (let parm of C.injectMe) {
if (typeof(parm) === "function") {
console.log("\t" + parm["typeName"]);
} else {
console.log("\t" + parm)
}
}
});
});
}
I've made a wrapper around express (but any web framework could be supported, an adapter interface is defined) with a decorator based API: https://github.com/cybrown/web-decorators
I am using ClassDecorator, ParameterDecorator and MethodDecorator.
@cybrown I just updated the signature for ParameterDecorator in #2635, which is now in master.
@rbuckton Thank you, I'll update that tomorow in my project.
Is it possible to have the name of the parameter in a ParameterDecorator ? This may be useful because I think that the name of the parameter might be half of the time the first argument of a ParameterDecorator. Moreover, it might be a solution to parameter name mangling by minifiers.
i've been asked to accomplish this:
@inject(A, B, "some key")
class C {
static injectMe: Array<any> = [];
constructor(a: A, b: B) {
}
}
function inject(...rest) {
return function(target): void {
target["inject"] = rest;
}
}
but without specifying the keys in the inject decorator, but instead having the decorators pick up the constructor's class functions automatically with something along these lines:
inject(@parameterTypes types:Function[]){ ... }
i'm looking for how to do what @jonathandturner describes here
@cmichaelgraham Yes having runtime type information (rtti as described in what was AtScript) would be awesome for that kind of usage, even in a completely separated feature such as introspection.
@cmichaelgraham look at https://github.com/Microsoft/TypeScript/pull/2589
@cmichaelgraham We are working on a proposal for ES7 to add a metadata API that will work together with decorators. #2589 adds experimental support for that proposal, but requires a separate polyfill be present to read the metadata.
@rbuckton @cmichaelgraham There was originally a design for special a TypeScript decorator that would tell the compiler to inject types into the decorator, based on the target being decorated. I think it was @parameterTypes Am I correct in thinking that that feature is being removed in favor of the more general metadata api? If so, I would support that.
Can you talk a bit about the status of that with respect to TypeScript. Is that planned for the release of 1.5? If so, what will the compiler options look like? One thing that would be useful is to have the compiler automatically generate the type metadata for constructor signatures only.
@EisenbergEffect Decorators are part of the 1.5, you can start using it with our latest release 1.5-alpha.
As for meta data support. The desing has changed since the orignal proposal for @paramtypes. the new desing is using Reflect.metada proposal. See #2589 for more details on how it works. also @rbuckton has a pollyfill to consume the metadata here: https://github.com/rbuckton/reflectDecorators