I’d like to use decorators in my project. Here’s what I have written:
JavaScript
x
15
15
1
export const DetachedWindow = (options: TDetachedWindowOptions = defaultOptions) => <R extends Constructable>(Clazz: R): R => {
2
const tmp = class extends Clazz {
3
value = 'value';
4
5
value2 = 'value2';
6
7
constructor(args: any[]) {
8
super(args);
9
// <some logick>
10
}
11
};
12
Object.defineProperty(tmp, 'name', { value: Clazz.name });
13
return tmp;
14
};
15
As you see this decorators creates a few fields. But typescript can’t recognize them
JavaScript
1
9
1
@DetachedWindow({ optA: 'optA' })
2
export class SomeClass {
3
constructor() {
4
setTimeout(() => {
5
console.log(this.value); // TS2339: Property 'value' does not exist on type 'SomeClass'.
6
});
7
}
8
}
9
It does exsist though. If I add @ts-ignore
before using these parameters, the code works okay.
I wounder, how can I create a class decorator, that would extend parent’s type. I tried to do something like this:
JavaScript
1
2
1
export const DetachedWindow = (options: TDetachedWindowOptions = defaultOptions) => <R extends Constructable>(Clazz: R): R & { value: string } => {
2
But it didn’t help.
Any ideas?
Advertisement
Answer
The answer is in the TypeScript docs of the Class decorators:
JavaScript
1
6
1
// Note that the decorator _does not_ change the TypeScript type
2
// and so the new property `reportingURL` is not known
3
// to the type system:
4
bug.reportingURL;
5
Property 'reportingURL' does not exist on type 'BugReport'.
6