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
@mhegazy I know that. See here: http://blog.durandal.io/2015/04/09/aurelia-update-with-decorators-ie9-and-more/ :smile:
I'm also familiar with the metadata proposal. I've been providing feedback on that. I just wanted to know if the original @parameterTypes idea was being removed.
thanks @EisenbergEffect for sharing. :+1:
Yes. the only issue with @paramtypes is it makes emit directed by the type system, and requiring global program information. This breaks scenarios for single-module transpilation (see #2499). The other option was to put it on call sites, which adds a lot of work on the decorator users instead of authors. So we went back to the drawing board and landed on the Reflect.metadata approach instead.
if you also looked at earlier versions of the proposal, we had to remove the ambient/design-time decorators for the same reason.
Thanks for clarifying. That all makes sense. Any idea if the Reflect-based approach will land in 1.5?
yes. it is currently in master. it should be available in the next release. it is currently an opt-in feature using the experimental flag --emitDecoratorMetadata; and it only adds metadata to decorated entities.
"it only adds metadata to decorated entities" Can you expand on that idea? Is a special decorator involved? Or does it add it to anything with any decorator? In other words, if a developer uses Aurelia's inject decorator, then will that trigger the compiler to generate the metadata?
if a developer uses Aurelia's inject decorator, then will that trigger the compiler to generate the metadata?
yes.
what i meant is:
@inject
class Foo {
constructor(a: number, b: string) {}
}
class Bar {
constructor(a: number, b: string) {}
}
with --emitDecoratorMetadata the compiler will emit type metadata (i.e. call to reflect.metadata('desing:paramtypes', [Number, String])) for Foo but not Bar.
That will work for us. We'll prepare support for the Reflect.metadata api for our next release, most likely next week. Thanks for the clarification!
so what is emitted for this?
@inject
class Foo {
constructor(a: A, b: B) {}
}
class Bar {
constructor(a: number, b: B) {}
}
would it be (for Foo):
reflect.metadata('desing:paramtypes', [A, B])
@cmichaelgraham Yes, that is roughly what is generated.
crazy cool !!!!
using gulp-typescript to build this repo - (nice work @ivogabe)
gulpfile build-ts command (note the emitDecoratorMetadata option):
gulp.task('build-ts', function () {
var tsResult = gulp.src([
'./views/*.ts',
'./typings/**/*.d.ts',
'./*.ts'
],
{base: "."})
.pipe(ts({
typescript: require('typescript'),
declarationFiles: false,
noExternalResolve: true,
target: "es5",
module: "amd",
emitDecoratorMetadata: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('.')),
tsResult.js.pipe(gulp.dest('.'))
]);
});
turns app.ts
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';
@inject(Router)
export class App {
public router;
constructor(router:Router) {
this.router = router;
this.router.configure(config => {
config.title = 'Aurelia';
config.map([
{ route: ['','welcome'], moduleId: './welcome', nav: true, title:'Welcome' },
{ route: 'flickr', moduleId: './flickr', nav: true },
{ route: 'child-router', moduleId: './child-router', nav: true, title:'Child Router' }
]);
});
}
}
into app.js
var __decorate = this.__decorate || (typeof Reflect === "object" && Reflect.decorate) || function (decorators, target, key, desc) {
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = this.__metadata || (typeof Reflect === "object" && Reflect.metadata) || function () { };
define(["require", "exports", 'aurelia-framework', 'aurelia-router', 'bootstrap', 'bootstrap/css/bootstrap.css!'], function (require, exports, aurelia_framework_1, aurelia_router_1, , ) {
var App = (function () {
function App(router) {
this.router = router;
this.router.configure(function (config) {
config.title = 'Aurelia';
config.map([
{ route: ['', 'welcome'], moduleId: './welcome', nav: true, title: 'Welcome' },
{ route: 'flickr', moduleId: './flickr', nav: true },
{ route: 'child-router', moduleId: './child-router', nav: true, title: 'Child Router' }
]);
});
}
App = __decorate([
aurelia_framework_1.inject(aurelia_router_1.Router),
__metadata('design:paramtypes', [aurelia_router_1.Router])
], App);
return App;
})();
exports.App = App;
});
of special interest is the emiited type metadata about the constructor parameters:
App = __decorate([
aurelia_framework_1.inject(aurelia_router_1.Router),
__metadata('design:paramtypes', [aurelia_router_1.Router])
], App);
so in theory, you could alter the inject decorator function to inject the proper classes without specifying them in the inject, but instead specifying the types in the constructor :)
@cmichaelgraham We can easily enable this today without altering the framework. The DI library from Aurelia has a hook container.addParameterInfoLocator. You pass it a function that can take a type and return its dependencies. For our next release (next week), we can add this to the core configuration though so it's easy for TypeScript developers to turn it on. I would have put it in this week's release, but I hadn't realized that this was changed yet.
@EisenbergEffect brilliant !! :+1:
I used annotations to mark properties of an object as observable, which transforms a primitive into an observable object (for those interested, https://github.com/mweststrate/MOBservable/commit/8cc7fc0e20c000db660037c8b5c9d944fe4155d9).
However, especially for properties, it felt a bit unnatural that the annotations are applied to the prototype, and not in the constructor of a class itself, this means that it is hard to either get the the initial value, or even the this. The work around for that was to create a property, and in its getter/setter perform the actual logic that the annotation was supposed to do, since the this and the value are available then.
Besides that, awesome feature!
Using Metadata Reflection API I was able to do a simple properties dependency injection. You can check required changes here https://github.com/matjaz/property-DI/commit/2b4835e100b72d954b57d0e656ea524539ac17eb.
Shouldn't be __metadata decorator in generated code invoked first of all decorators? I wanted to create simple deocrator using class's metadata, but __metadata('design:paramtypes', [TYPES....]) is invoked as last, so i can not get these data from Reflect
@ufon can you share the code you are looking at?
Sure, here https://gist.github.com/ufon/5a2fa2481ac412117532
EDIT: my bad, there is some other mistake in my code, cannot get types even after class inicialization
@ufon, i am not sure i see the issue then. __metadata is the last item in the decorator list, this means it is the first to execute, and definitely before inject gets to execute.
House = __decorate([
inject_1.inject,
__metadata('design:paramtypes', [Floor, String])
], House);
where __decorate definition uses reduce right to execute the decorators in reverse order.
decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
This is to match the spec, that decorators (as expressions) are evaluated in order of declaration, but executed in the reverse order, allowing outer decorators to consume results from inner decorators.
I see, sorry for annoy :) my bad, there is some other mistake in my code, cannot get types even after class inicialization