'typescript: decorator in abstract method
I have the following class:
export abstract class CanDeactivateComponent {
abstract canLeavePage(): boolean;
abstract onPageLeave(): void;
@someDecorator
abstract canDeactivateBeforeUnload(): boolean;
}
and I get the error A decorator can only decorate a method implementation, not an overload
. I understand I can not put a decorator in that case but, which workaround can be applied so that I force all implementations of this class to use @someDecorator
before canDeactivateBeforeUnload
? Isn't there any way to put this decorator in the abstract class itself so that I don't have to write it in all the implementations?
Thank you!
Solution 1:[1]
I guess it depends on the context, but perhaps using a method that proxies can work for you?
export abstract class CanDeactivateComponent {
abstract canLeavePage(): boolean;
abstract onPageLeave(): void;
abstract canDeactivateBeforeUnload(): boolean;
@someDecorator
_canDeactivateBeforeUnload(): boolean {
return this.canDeactivateBeforeUnload()
}
}
Solution 2:[2]
Inspired by Rengers's answer and apokryfos's comment:
tsconfig.json
:
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
example.ts
:
#!/usr/bin/env ts-node
export function SomeDecorator(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
console.log('SomeDecorator called');
}
export abstract class ExampleComponent {
abstract _canDoTheThing(): boolean;
@SomeDecorator
canDoTheThing(): boolean {
return this._canDoTheThing();
}
}
class ExampleComponentImpl extends ExampleComponent {
_canDoTheThing(): boolean {
return true;
}
}
new ExampleComponentImpl().canDoTheThing();
chmod u+x ./example.ts && ./example.ts
Output:
SomeDecorator called
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rengers |
Solution 2 | GabLeRoux |