Skip to content

Instantly share code, notes, and snippets.

@pablorsk
Last active January 26, 2023 15:17
Show Gist options
  • Save pablorsk/821bd55acefddd95e474652818e41462 to your computer and use it in GitHub Desktop.
Save pablorsk/821bd55acefddd95e474652818e41462 to your computer and use it in GitHub Desktop.
TypeScript Decorator: Run code before and after class constructor()
function ClassWrapper() {
return function(target: any) {
// save a reference to the original constructor
var original = target;
// the new constructor behaviour
var f: any = function (...args) {
console.log('ClassWrapper: before class constructor', original.name);
let instance = original.apply(this, args)
console.log('ClassWrapper: after class constructor', original.name);
return instance;
}
// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
};
}
@ClassWrapper()
export class ClassExample {
public constructor() {
console.info('Running ClassExample constructor...');
}
}
let example = new ClassExample();
/*
CONSOLE OUTPUT:
ClassWrapper: before class constructor ClassExample
Running ClassExample constructor...
ClassWrapper: after class constructor ClassExample
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment