Search code examples
typescriptdecoratortypescript2.2

How to parametrize the class decorator function?


I have the following test code, collected from examples in the internet:

function Dec(target: any) {
  console.log("Dec called with: " + JSON.stringify(target));
}

@Dec
class C {
  public x: number = 0;
  constructor() {
    this.x = 5;
  }
  show() {
    console.log("C.show(): " + this.x);
  }
}

let c = new C();
c.show();

Compiling with tsc --experimentalDecorators test.ts I get no warning or any problem. But calling it (with a node test.js command), I get the following result:

Dec called with: undefined
C.show(): 5

I think, the decorators doesn't work on the way, as the most examples (for typescript 1.5) around on the net shows.

How to implement this decorator correctly?


The resulting javascript code is this:

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function Dec(target) {
    console.log("Dec called with: " + JSON.stringify(target));
}
var C = (function () {
    function C() {
        this.x = 0;
        this.x = 5;
    }
    C.prototype.show = function () {
        console.log("C.show(): " + this.x);
    };
    return C;
}());
C = __decorate([
    Dec
], C);
var c = new C();
c.show();

Solution

  • From the Documentation:

    The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.

    The argument being passed as target is actually the constructor function of your C class (and not the actual instance created). Obviously, trying to JSON.stringify a function reference will yield undefined as a result.