小编Wil*_*ill的帖子

尽管设置了元数据,Reflect.getMetadata() 返回未定义

我正在尝试在我的 TypeScript 应用程序中使用注释。然而,我一定做错了什么,因为Reflect.getMetadata()总是返回undefined,尽管我可以在调试器中看到元数据似乎设置正确。

my-class.ts 带有带注释的属性:

import { jsonIgnore } from './json-ignor';

export class MyClass {
    public prop1: string;
    @jsonIgnore() public prop2: string;
}
Run Code Online (Sandbox Code Playgroud)

json-ignore.ts 带有装饰和注释功能:

const JSON_IGNORE = 'jsonIgnore';

export function jsonIgnore(): any {
    return Reflect.metadata(JSON_IGNORE, true);
}

export function jsonIgnoreReplacer(key: string, value: any): any {
    const meta = Reflect.getMetadata(metadataKey, object, propertyKey);
    // do something with the metadata...
}
Run Code Online (Sandbox Code Playgroud)

现在meta总是undefined。但是当我在调试器中检查MyClass实例时,我看到它的原型中设置了元数据:

  • 我的班级:我的班级
    • 道具1:'foo'
    • 道具2:'酒吧'
    • [[原型]]:对象
      • __元数据__:
        • 道具2:
          • json忽略:true

我还可以轻松访问__metadata__及其条目 …

annotations metadata typescript reflect decoration

5
推荐指数
1
解决办法
1739
查看次数

标签 统计

annotations ×1

decoration ×1

metadata ×1

reflect ×1

typescript ×1