Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created February 25, 2016 07:28
Show Gist options
  • Save jchadwick/41075d9a90aeda769d1c to your computer and use it in GitHub Desktop.
Save jchadwick/41075d9a90aeda769d1c to your computer and use it in GitHub Desktop.
TypeScript Decorators
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;
}
}
}
}
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