Created
December 22, 2018 04:50
-
-
Save mohanramphp/8bdd8946a8f2e5d6cc2bcb6e0b3f0253 to your computer and use it in GitHub Desktop.
Metadata Reflection API Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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