Skip to content

Instantly share code, notes, and snippets.

@khalidx
Created June 7, 2021 01:57
Show Gist options
  • Save khalidx/37b5667cda0e2c5583a4540cb2234fdd to your computer and use it in GitHub Desktop.
Save khalidx/37b5667cda0e2c5583a4540cb2234fdd to your computer and use it in GitHub Desktop.
Quickly create a TypeScript Decorator.

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment