Last active
January 26, 2023 15:17
-
-
Save pablorsk/821bd55acefddd95e474652818e41462 to your computer and use it in GitHub Desktop.
TypeScript Decorator: Run code before and after class constructor()
This file contains hidden or 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 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