Skip to content

Instantly share code, notes, and snippets.

@siandreev
Created October 20, 2021 11:39
Show Gist options
  • Save siandreev/4b7870625243463c70b4d7123ee56b14 to your computer and use it in GitHub Desktop.
Save siandreev/4b7870625243463c70b4d7123ee56b14 to your computer and use it in GitHub Desktop.
ClassDecorator
@logClass
class Person {
public name: string;
constructor(name : string) {
this.name = name;
}
public myMethod() {
console.log('method works!');
}
}
function logClass<TFunction extends Function>(target: TFunction): TFunction {
const newConstructor = function(...args) {
console.log(`New instance of ${target.name}: ${args}`);
return target.apply(this, args);
}
newConstructor.prototype = target.prototype;
return newConstructor as unknown as TFunction;
}
const p1 = new Person('Person 1');
const p2 = new Person('Person 2');
p1.myMethod();
console.log(p1 instanceof Person)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment