无法获取反映类实例的元数据

时间:2018-11-05 13:57:54

标签: typescript reflect-metadata

我正在尝试从类的实例中检索反射元数据。 docs上的示例表明应该可以,但我正在使用undefined。但是,如果我从类本身请求元数据,则与方法相同,我将获取数据。

例如,这是完整的示例脚本:

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

我的目标是取回classInstanceMetadata中的一些数据,使我可以将其与类类型相关联。

2 个答案:

答案 0 :(得分:0)

发现我需要使用装饰器,然后在目标的原型上定义元数据。

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'
  }
}

答案 1 :(得分:0)

我认为您可以在装饰器上省略(),所以@Decorate就足够了。另外,reflect具有特定的元数据设计键,具体取决于元数据/装饰器的使用:

  1. 类型元数据= "design:type"
  2. 参数类型元数据=> "design:paramtypes"
  3. 返回类型元数据=> "design:returntype"