-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdecorators.ts
50 lines (42 loc) · 1.25 KB
/
decorators.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
type Constructor = { new (...args: any[]): {} };
export function functionReturnsClasstype<T extends Constructor>(ctr: T) {
return class extends ctr {
};
}
/**
* A class decorator that changes inherited state and adds a readonly field to the class.
*
* This wasn't the thing that was exploding, see `function-returning-anonymous-class.ts` for that.
* Nevertheless, this makes for a good class decorator demo.
*/
export function classDecorator(x: typeof SomeDecoratedClass): typeof SomeDecoratedClass {
const ret = class extends x {
constructor() {
super();
this.state = this.state + this.state;
}
};
// This adds a field to the class, but we can't reflect that in the type because of the limitations
// of decorators. That's we advertise it through interface merging below.
(ret.prototype as any)['field'] = 'some_added_field';
return ret;
}
@classDecorator
export class SomeDecoratedClass {
protected state = 'state';
public accessState() {
return this.state;
}
}
export interface SomeDecoratedClass {
readonly field: string;
}
/**
* Exercise the above code
*/
function tryDecoratedClass() {
const instance = new SomeDecoratedClass();
return instance.field;
}
// Suppress unused locals warnings
void tryDecoratedClass;