Cannot get reflect metadata of class instance

4.5k views Asked by At

I'm trying to retrieve the reflect-metadata from the instance of a class. The examples on the docs shows that it should be possible but I'm getting undefined. However if I request the metadata from the class itself, I get back the data, same with the method.

For eg, this is the full example script:

import 'reflect-metadata'

const metadataKey = 'some-key'

@Reflect.metadata(metadataKey, 'hello class')
class C {
  @Reflect.metadata(metadataKey, 'hello method')
  get name(): string {
    return 'text'
  }
}

let obj = new C()
let classInstanceMetadata = Reflect.getMetadata(metadataKey, obj)
console.log(classInstanceMetadata) // undefined

let classMetadata = Reflect.getMetadata(metadataKey, C)
console.log(classMetadata) // hello class

let methodMetadata = Reflect.getMetadata(metadataKey, obj, 'name')
console.log(methodMetadata) // hello method

My goal is to get back some data in the classInstanceMetadata that lets me associate it with the class type.

2

There are 2 answers

0
Shawn Mclean On BEST ANSWER

Found out that I'll need to use a decorator and then define the metadata on the target's prototype.

import 'reflect-metadata'

const metadataKey = 'some-key'

export const Decorate = (): ClassDecorator => {
  return (target: Function) => {
    @Reflect.metadata(metadataKey, 'hello class', target.prototype)
  }
}

@Decorate()
class C {
  get name(): string {
    return 'text'
  }
}
0
RodebertX On

I think u can omit () at the decorator, so @Decorate would be enough. Also, reflect has specific metadata design keys that depend on the use of the metadata/decorator:

  1. Type metadata = "design:type"
  2. Parameter type metadata => "design:paramtypes"
  3. Return type metadata => "design:returntype"