An example of a TypeScript Method Decorator, also known as an "annotation" in other languages.
You can use a decorator like @Decorator
on a method inside of a class
.
export function Decorator <Args extends any[], Result extends any> (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: Args) => Result>) {
const originalMethod = descriptor.value // save a reference to the original method
// NOTE: Do not use arrow syntax here. Use a function expression in
// order to use the correct value of `this` in this method (see notes below)
if (originalMethod) {
descriptor.value = function(...args: Args): Result {
// pre
console.log(target, propertyKey, "The method args are: " + JSON.stringify(args))
// run and store result
const result = originalMethod.apply(this, args)
// post
console.log(target, propertyKey, "The return value is: " + result)
// return the result of the original method (or modify it before returning)
return result
}
}
return descriptor
}