Skip to content

Instantly share code, notes, and snippets.

@vvakame
Created April 12, 2015 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vvakame/cfc603535f4fec35838e to your computer and use it in GitHub Desktop.
Save vvakame/cfc603535f4fec35838e to your computer and use it in GitHub Desktop.
TypeScript 1.5.0-alpha でどういうdecoratorsの使い方ができるか調べてみた。他にもパターンあったらコメントに書いてください。お願いします!なんでもはしませんから!!
// https://github.com/Microsoft/TypeScript/issues/2249
function classDecorator(sampleClazz: typeof Sample): typeof Sample {
console.log("classDecorator", arguments);
sampleClazz.prototype.a = function() {
return "Hello from classDecorator!";
}
return null; // 値を返すとその値で置き換えることができる
}
function methodDecorator(prototypeOfSample: any, key: string, propertyDescription: PropertyDescriptor): PropertyDescriptor {
console.log("methodDecorator", arguments);
return null; // 値を返すとその値で置き換えることができる
}
function staticMethodDecorator(sampleClazz: typeof Sample, key: string, propertyDescription: PropertyDescriptor): PropertyDescriptor {
console.log("staticMethodDecorator", arguments);
return null; // 値を返すとその値で置き換えることができる
}
function propertyDecorator(prototypeOfSample: any, key: string): void {
console.log("propertyDecorator", arguments);
}
function accessorDecorator(prototypeOfSample: any, key: string, propertyDescription: PropertyDescriptor): PropertyDescriptor {
console.log("accessorDecorator", arguments);
return null; // 値を返すとその値で置き換えることができる
}
function parameterDecorator(prototypeOfSample: any, methodName: string, parameterIndex: number): void {
console.log("parameterDecorator", arguments);
// DIや呼び出し時に実行を行いたい場合はメソッドの差し込みを自力で実装する必要がありそう
}
@classDecorator
class Sample {
a(): string {
return "";
}
@methodDecorator
b(): string {
return "";
}
@staticMethodDecorator
static c(): string {
return "";
}
@propertyDecorator
d = "";
@accessorDecorator
get e(): string {
return "";
}
f(@parameterDecorator str: string): string {
return `Hello, ${str}`;
}
}
console.log("------");
let obj = new Sample();
console.log(obj.a());
console.log(obj.b());
console.log(Sample.c());
console.log(obj.d);
console.log(obj.e);
console.log(obj.f("parameter"));
@vvakame
Copy link
Author

vvakame commented Apr 12, 2015

@okunokentaro
Copy link

class A {
  constructor(){}
}

class B extends A {
  constructor(){super()}
}

@A()
class HogeController {}

@B()
class FugaController {}

Angular 2の実装パターンです。Babel 5.0.12はnewを付けないconstructorの使用を認めないので例外を吐きます。

@okunokentaro
Copy link

class A {
  constructor(){}
}

class B {
  constructor(){}
}

@A()
@B()
class HogeController {}

こういうパターンもあります、2重decorator。
実装はこちらに。

https://github.com/angular/angular/blob/master/modules/angular2/src/core/annotations/annotations.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment