One log decorator to rule them all

One log to rule them all

In a previous post we looked at implementing log decorators using the experimental features of TypeScript.

Obviously it’d be far nicer if we had a single log decorator that we can apply to each place where a decorator might be used, i.e. a log decorator which can be used instead of logClass, logMethod etc. We can simply create a log function which takes any number of arguments and have this delegate to the specific log function as required (a factory function basically). I’m not going to write the whole thing here, but something along the lines of (the following code) would do the job

function log(...args: any[]): void {
  switch(args.length) {
    case 1: 
      // return logClass
    case 2: 
      // return logProperty     
    case 3: 
      return (typeof args[2] === "number") ? 
        logParameter :
        logMethod
      default:
         throw new Error();    
   }
}