When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen?
I've got some code that demonstrates the issue:
- First, a decorator is created which replaces the constructor of a class with a new one that should essentially perform the same task.
- Next, a base class with a property is defined.
- The base class is then wrapped with the decorating function.
- A subclass is created that extends the base class.
- Now when trying to access the property on the extended class, it fails to retrieve the value.
Take a look at the code snippet below:
function wrap(target: any) {
// the new constructor
var f: any = function (...args) {
return new target();
}
f.prototype = target.prototype;
return f;
}
@wrap
class Base {
prop: number = 5;
}
class Extended extends Base {
constructor() {
super()
}
}
var a = new Extended()
console.log(new Extended().prop) // I'm expecting 5 here, but I get undefined.
It seems like there's a subtlety related to either prototypes in general or the specific way TypeScript handles them that I haven't fully grasped yet.