クラス・メソッド・プロパティにメタデータや動作を付与する
// experimentalDecoratorsが必要
function Log(target: any, key: string, desc: PropertyDescriptor) {
const orig = desc.value;
desc.value = function(...args: any[]) {
console.log(`${key} called with`, args);
return orig.apply(this, args);
};
}
class Calculator {
@Log
add(a: number, b: number) { return a + b; }
}Angular/NestJSで多用される。TC39のステージ3デコレータ提案(新仕様)とexperimentalDecoratorsで挙動が異なる場合があるため注意。