Created
January 22, 2016 13:26
-
-
Save frontdevops/b77b769c5a599afd4555 to your computer and use it in GitHub Desktop.
TypeScript parameter and metadata decorators 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
"use strict"; | |
function logParameter(target:Object, key:string, index:number) { | |
var metadataKey = `log_${key}_parameters`; | |
if (Array.isArray(target[metadataKey])) { | |
target[metadataKey].push(index); | |
} | |
else { | |
target[metadataKey] = [index]; | |
} | |
} | |
function logMethod(target:Object, key:string, descriptor:any) { | |
var originalMethod = descriptor.value; | |
descriptor.value = function (...args:any[]) { | |
var indices = target[`__log_${key}_parameters`]; | |
if (Array.isArray(indices)) { | |
for (let i = 0; i < args.length; i++) { | |
if (indices.indexOf(i) !== -1) { | |
let arg = args[i]; | |
let argStr = JSON.stringify(arg) || arg.toString(); | |
console.log(`${key} arg[${i}]: ${argStr}`); | |
} | |
} | |
return originalMethod.apply(this, args); | |
} | |
let a = args.map(a => (JSON.stringify(a) || a.toString())).join(); | |
let result = originalMethod.apply(this, args); | |
let cln = target.constructor.name; | |
console.log(`Call: ${cln}.${key}(${a}) => ${JSON.stringify(result)}`); | |
return result; | |
}; | |
return descriptor; | |
} | |
class Person { | |
constructor( | |
public name:string, | |
public surname:string | |
){} | |
@logMethod | |
public say(@logParameter message:string):string { | |
return `${this.name} ${this.surname} says: ${message}`; | |
} | |
} | |
let me = new Person("Alex", "Mayorov"); | |
let you = new Person("Kira", "Hagakyre"); | |
me.say('Hi, Kira!'); | |
you.say('Hi, Alex!'); | |
/* Output: | |
Call: Person.say("Hi, Kira!") => "Alex Mayorov says: Hi, Kira!" | |
Call: Person.say("Hi, Alex!") => "Kira Hagakyre says: Hi, Alex!" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment