I'm trying to use annotations in my TypeScript application. However I must be doing something wrong, as Reflect.getMetadata()
always returns undefined
, although I can see in the debugger that the metadata seems to be set correctly.
my-class.ts with an annotated property:
import { jsonIgnore } from './json-ignor';
export class MyClass {
public prop1: string;
@jsonIgnore() public prop2: string;
}
json-ignore.ts with the decoration and annotation function:
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...
}
Now meta
is always undefined
. But when I check the MyClass
instance in the debugger, I see that it has the metadata set in its prototype:
- myClass: MyClass
- prop1: 'foo'
- prop2: 'bar'
- [[Prototype]]: Object
- __metadata__:
- prop2:
- jsonIgnore: true
- prop2:
- __metadata__:
I can also access the __metadata__
and it's entries easily (Object.getPrototypeOf(myClass).__metadata__.prop2.jsonIgnore
), but that's definitely a hack when there is an API for it and will most likely not work in different browsers?
So if anyone could point out what I'm doing wrong... that would be very much appreciated!
More info: tsconfig.json:
"compilerOptions": {
...
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
}
It looks like you have defined your metadatakey as a string. Following the instructions in the TypeScript docs here, you need to define the key as a Symbol. I've also noticed that the Symbol actually needs to be the same instance in the decorator and the function that uses the metadata. Try this: