Skip to content

Instantly share code, notes, and snippets.

@mohanramphp
Created December 22, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohanramphp/8bdd8946a8f2e5d6cc2bcb6e0b3f0253 to your computer and use it in GitHub Desktop.
Save mohanramphp/8bdd8946a8f2e5d6cc2bcb6e0b3f0253 to your computer and use it in GitHub Desktop.
Metadata Reflection API Example
import "reflect-metadata";
// parameter decorator uses reflect api to store the indexes of the decorated parameter
export function logParameter(target: Object, propertyName: string, index: number) {
// to get the metadata from the target object
const indices = Reflect.getMetadata(`log_${propertyName}_parameters`, target, propertyName) || [];
indices.push(index);
// to define the metadata to the target object
Reflect.defineMetadata(`log_${propertyName}_parameters`, indices, target, propertyName);
}
// property decorator uses reflect api to get the run time type of the property
export function logProperty(target: Object, propertyName: string): void {
// to get the design type of the property from the object
var t = Reflect.getMetadata("design:type", target, propertyName);
console.log(`${propertyName} type: ${t.name}`); // name type: String
}
class Employee {
@logProperty
private name: string;
constructor(name: string) {
this.name = name;
}
greet(@logParameter message: string): string {
return `${this.name} says: ${message}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment