Typescript Reflect-MetaData in nodejs

5.2k Views Asked by At

Does anyone have any examples of how to use reflect-metadata in nodejs? I am using atom-typescript also. I downloaded using it via npm but i keep getting random errors. I see Reflect is a blank object. Just looking for an example of how to incorporate this into a module or node project.

2

There are 2 best solutions below

0
On BEST ANSWER

In [email protected]+, you can use it like this:

npm i -S reflect-metadata
npm i -D @types/reflect-metadata

// your.ts
import 'reflect-metadata'
Reflect.getMetadata(...)
Reflect.metadata(...)
1
On

When I faced the same problem and nothing worked, I opened Reflect.ts file in node_modules. At the end, you can see it hooking Reflect at global level.

// hook global Reflect
(function(__global: any) {
    if (typeof __global.Reflect !== "undefined") {
        if (__global.Reflect !== Reflect) {
            for (var p in Reflect) {
                __global.Reflect[p] = (<any>Reflect)[p];
            }
        }
    }
    else {
        __global.Reflect = Reflect;
    }
})(
    typeof window !== "undefined" ? window :
        typeof WorkerGlobalScope !== "undefined" ? self :
            typeof global !== "undefined" ? global :
                Function("return this;")());

So, I removed require reflect-metadata from all other files, and moved it to main file.

require('reflect-metadata/Reflect');

Now, I can use it inside all modules (without requiring reflect-metadata) with the following syntax,

(<any>global).Reflect.getMetadata("design:type", target, key); // In Typescript

EDIT: We can also reference reflect-metadata.d.ts file from node_modules and then use the API directly.

/// <reference path="../../node_modules/reflect-metadata/reflect-metadata.d.ts" />

Reflect.getMetadata("design:type", target, propertyKey);