2

So I have a TypeScript project I am working on and I want to make use of the reflect-metadata package. I am a little confused about the correct way of importing this. It was my understanding that this only needed to be imported once in your "main" file. So in my case I have an app.ts in which I import reflect-metadata as the very first thing:

import 'reflect-metadata';

import ReflectionClass from '@src/Reflection/ReflectionClass';
...

ReflectionClass then in turn imports another class that eventually calls Reflect.getMetadata(). However, this fails with error

error TS2339: Property 'getMetadata' does not exist on type 'typeof Reflect'.

Only when I import reflect-metadata explicitly in the relevant file does the error disappear. Is this the correct way to do this? In other words, do I need to import reflect-metadata in each file that uses it as opposed to a global, one time import in your main file?

Mikey Dee
  • 91
  • 3
  • 10

2 Answers2

2

To answer my own question; yes, you only have to import it once. I did some overall project re-arrangement which among others involved replacing ts-node for a rollup based solution and removing a bunch of unused packages. After that a single import of reflect-metada now does work. Unfortunately I cannot deduce the exact cause of my original problem, only that it is solved now after reorganisation. Perhaps some other package was interfering with it.

Mikey Dee
  • 91
  • 3
  • 10
1

Yes, this is because there is no export in the package of reflect-metadata.

pungggi
  • 1,263
  • 14
  • 25
  • Not sure I follow you. Doesn't _reflect-metada_ simply add additional functionality to the global Reflect object by means of Object.defineProperty? So there is no need to define an export. And come to think of it, there also shouldn't be a need to import it multiple times. – Mikey Dee Nov 20 '18 at 20:48