我正在尝试在我的 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实例时,我看到它的原型中设置了元数据:
我还可以轻松访问__metadata__及其条目 …