Reputation: 1496
I'd like to extend a class with decorators but don't know how exactly. My current approach is as follows:
function Foo(value: string) {
return function(target: Function) {
let injected = Object.assign(target.prototype, { foo: value });
return injected;
}
}
@Foo("Hello world")
class Bar {
}
let instance = new Bar();
console.log(instance.foo); // Should say "Hello World"
But I can't instantiate my class anymore: "TypeError: Bar is not a constructor".
Where's my mistake?
Upvotes: 2
Views: 3370
Reputation: 1482
You don't have to return a new object from the decorator. In this case target object will be modified, so just
function Foo(value: string) {
return function(target: Function) {
Object.assign(target.prototype, { foo: value });
}
}
should work fine
Upvotes: 1