メモログ

⛰ 塵が積もって山とならないメモのログ 👄

Angular2とDecorators

Decorators は ECMAScript で Propose となっている実装で、Angular 2 と TypeScript を使った実装ではよく出てくる。 Exploring ES2016 Decorators – Google Developers – Mediumを参考にすると、定義したfunction名の頭に「@」をつけて、使いたいclassやpropertyの前に記述するらしい。

An ES2016 decorator is an expression which returns function and can take a target, name and property descriptor as arguments. You apply it by prefixing the decorator with an @ character and placing this at the very top of what you are trying to decorate. Decorators can be defined for either a class or property.

Exploring ES2016 Decorators – Google Developers – Mediumに記述されているサンプルコード(一部)は下記のような感じ。

function readonly(target, key, descriptor){
  descriptor.writable = false;
  return descriptor
}
class Cat {
  @readonly
  meow() { return `${this.name} says Meow`; }
}

上記の例の場合、meow functionオブジェクトの writable プロパティが false に設定される。

Angular.ioの5 Min Quickstartでは、下記のようなサンプルコードが載っている。@ComponentのDecoratorsで設定したプロパティが、AppComponentに設定される。

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: 'My First Angular 2 App'
})
export class AppComponent { }

(なお、TypeScriptをJavascriptにcompileする場合には、tsconfigのcompilerOptionsで”experimentalDecorators”: trueの設定が必要がある。)

という感じのメモ(書いてみたら大して書くこと思いつかなかった)。

そのほか参考: