How to properly wrap constructors with decorators in TypeScript
The comments in the other answers complain that code doesn't work.
Actually, it works, but not in jsFiddle...
It is an issue with the code generation in jsFiddle (perhaps using an obsolete version of TypeScript).
The code above works with TypeScript 2.7.2 (run with Node).
So this is basically the code in pablorsk's answer (except there is no need to return the instance), I just added full types to please a stricter TSLint...
function logClass<T extends { new(...args: any[]): {} }>(): any {
type Ctor = new (...args: any[]) => T;
return (target: T): Ctor => {
// Save a reference to the original constructor
const Original = target;
// the new constructor behaviour
let decoratedConstructor: any = function (...args: any[]): void {
console.log("Before construction:", Original);
Original.apply(this, args);
console.log("After construction");
};
// Copy prototype so intanceof operator still works
decoratedConstructor.prototype = Original.prototype;
// Copy static members too
Object.keys(Original).forEach((name: string) => { decoratedConstructor[name] = (<any>Original)[name]; });
// Return new constructor (will override original)
return decoratedConstructor;
};
}
@logClass()
class Base {
prop = 5;
constructor(value: number) {
console.log("Base constructor", value);
this.prop *= value;
}
foo() { console.log("Foo", this.prop); }
static s() { console.log("Static s"); }
}
class Extended extends Base {
constructor(init: number) {
super(init);
console.log("Extended constructor", init);
}
bar() { console.log("Bar", this.prop); }
}
const b = new Base(2);
console.log("Base", b instanceof Base);
b.foo();
Base.s();
const e = new Extended(5);
console.log("Extended", e instanceof Base, e instanceof Extended);
e.bar();
[EDIT] Also added a line copying static members, otherwise decorated class throws an error when calling the static method.
This code works for me:
function logClass(target: any) {
// save a reference to the original constructor
var original = target;
// the new constructor behaviour
var f : any = function (...args) {
console.log("New: " + original.name);
//return original.apply(this, args);
return new original(...args); // according the comments
}
// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
}
@logClass
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var b = new Base()
console.log(b.prop)
var a = new Extended()
console.log(a.prop)
A solution using ES2015 Proxy to override the constructor:
function wrap(target: any) {
return new Proxy(target, {
construct(clz, args) {
console.log(`Constructing ${target.name}`);
return Reflect.construct(clz, args);
}
});
}
@wrap
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var a = new Extended()
console.log(new Extended().prop);
You can also run this on StackBlitz
This is the more modern approach using the latest TS (3.2.4). The below also uses the decorator factory pattern so you can pass in attributes:
function DecoratorName(attr: any) {
return function _DecoratorName<T extends {new(...args: any[]): {}}>(constr: T){
return class extends constr {
constructor(...args: any[]) {
super(...args)
console.log('Did something after the original constructor!')
console.log('Here is my attribute!', attr.attrName)
}
}
}
}
See here for more info: https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators