Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 无法获取类实例的反射元数据_Typescript_Reflect Metadata - Fatal编程技术网

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

Typescript 无法获取类实例的反射元数据,typescript,reflect-metadata,Typescript,Reflect Metadata,我试图从类的实例中检索反射元数据。上的示例表明这应该是可能的,但我得到了未定义的。但是,如果我从类本身请求元数据,我会返回数据,方法也是如此 例如,这是完整的示例脚本: import 'reflect-metadata' const metadataKey = 'some-key' @Reflect.metadata(metadataKey, 'hello class') class C { @Reflect.metadata(metadataKey, 'hello method')

我试图从类的实例中检索反射元数据。上的示例表明这应该是可能的,但我得到了未定义的
。但是,如果我从类本身请求元数据,我会返回数据,方法也是如此

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

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
中获取一些数据,让我将其与类类型关联。

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

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'
  }
}
我想你可以在装饰师那里省略
()
,所以
@decoration
就足够了。此外,reflect具有特定的元数据设计键,这些键取决于元数据/装饰器的使用:

  • 类型元数据=
    “设计:类型”
  • 参数类型元数据=>
    “设计:参数类型”
  • 返回类型元数据=>
    “设计:返回类型”