Last active
January 22, 2016 14:54
-
-
Save frontdevops/7809b855b43baa1d6d24 to your computer and use it in GitHub Desktop.
TypeScript property decorator 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"; | |
/** | |
* Декоратор для логирования свойств | |
* @param target | |
* @param key | |
*/ | |
function logprop(target:any, key:string):any { | |
var val:any, | |
pool:{} = {}, | |
kn:string, | |
isStatic:boolean = target.hasOwnProperty(key); | |
if (isStatic) { | |
val = target[key] | |
} | |
else { | |
kn = target.constructor.name; | |
if (!pool[kn] ) pool[kn] = {}; | |
if (!pool[kn][key]) pool[kn][key] = null; | |
val = pool[kn][key]; | |
} | |
const get = ():any => { | |
console.log(`Get: ${key} => ${val}`); | |
return val; | |
}; | |
const set = (newVal):void => { | |
console.log(`Set: ${key} => ${newVal}`); | |
val = newVal; | |
}; | |
if (target.hasOwnProperty(key)) | |
return { get, set }; | |
if (delete pool[kn][key]) | |
Object.defineProperty(target, key, { get, set }); | |
} | |
class Person { | |
@logprop public name:string; | |
@logprop public surname:string; | |
@logprop public static vip:boolean = false; | |
constructor(name:string, surname:string) { | |
this.name = name; | |
this.surname = surname; | |
} | |
} | |
let me = new Person("Alex", "Mayorov"); | |
me.name = "Alexander M."; | |
me.name; | |
Person.vip; | |
Person.vip = true; | |
Person.vip; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment