Search code examples
typescriptreflect-metadata

Typescript emits no decorator metadata


I have a typescript project and would like to inspect some objects. So I installed reflect-metadata, enabled experimentalDeorators and emitDecoratorMetadata in tsconfig.json. Then I have this code:

import 'reflect-metadata';
class Bla {
    thing: string;
}
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));

It outputs undefined. I'd expect to get String or something else. Also, the compiled Javascript looks like this:

var Bla = /** @class */ (function () {
    function Bla() {
    }
    return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));

There is no code to set the metadata. Interestingly, in the moment I add a custom decorator, I see code emitted for setting metadata:

function deco(target, key) { }
var Bla = /** @class */ (function () {
    function Bla() {
    }
    __decorate([
        deco,
        __metadata("design:type", String)
    ], Bla.prototype, "thing", void 0);
    return Bla;
}());
console.log(Bla, Reflect.getMetadata('design:type', Bla, 'thing'));

But still I get undefined. I also tried Bla.prototype, no change. Any idea what's wrong here?


Solution

  • This is by design, decorator metadata is emitted only on decorated members. This is the PR and the issue it references, the title and first line say it all:

    Emit serialized design-time type metadata for decorators

    Add support behind an experimental compiler option to emit design-type metadata for decorated declarations in source.

    (Emphasis added )

    The issue when you add the decorator is that you need to inspect the prototype:

    import 'reflect-metadata';
    function deco(target, key) { }
    class Bla {
        @deco thing: string;
    }
    console.log(Reflect.getMetadata('design:type', Bla.prototype, 'thing')); // outputs String