Created
February 25, 2016 07:28
-
-
Save jchadwick/41075d9a90aeda769d1c to your computer and use it in GitHub Desktop.
TypeScript Decorators
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
function createSignature(instance, property, args) { | |
var className = instance.constructor.name, | |
argsString = args.map(JSON.stringify).join(', '); | |
return `${className}.${property}(${argsString})`; | |
} | |
export function LogMethodDecorator(): MethodDecorator { | |
return function(target, property: string, descriptor: TypedPropertyDescriptor<Function>) { | |
let method = descriptor.value; | |
return { | |
value: function(...args) { | |
var out = method.apply(this, arguments); | |
let signature = createSignature(target, property, args), | |
retValueString = JSON.stringify(out); | |
console.log(`${signature} => ${retValueString}`) | |
return out; | |
} | |
} | |
} | |
} |
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
function getValidators(target) { | |
return this.__validators || (this.__validators = []); | |
} | |
export function ValidatableDecorator(): ClassDecorator { | |
return function(target) { | |
target.prototype.validate = function validate() { | |
let validators = getValidators(this); | |
for(let validator of validators) { | |
let isValid = validator(this); | |
if(!isValid) | |
return false; | |
} | |
return true; | |
} | |
} | |
} | |
export function RequiredDecorator(): PropertyDecorator { | |
return function(target, key) { | |
let validators = getValidators(this); | |
validators.push(function(instance) { | |
var value = instance[key], | |
isValid = (value || value === false); | |
if(!isValid) { | |
console.log(`${key} is required`) | |
} | |
return isValid; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment