-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.ts
97 lines (79 loc) · 2.38 KB
/
example.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* eslint-disable no-console */
/* eslint-disable no-shadow */
import { Trait, traitSelector, Use } from './trait';
// Setup
class GetImageTrait extends Trait {
public static INSTANCE = 'toto';
public static S1 = 'Static1';
public static S2 = 'Static2';
public getImage(p1?: string, p2 = true) {
console.log('GetImageTrait.getImage');
// i.e. make a request to retrieve an image
return null;
}
}
class ComputeTrait extends Trait {
public compute() {
// i.e. compute anything
}
public getImage() {
console.log('ComputeTrait.getImage');
}
}
// 1. Simple Usage
console.log('======= EXAMPLE 1');
@Use(GetImageTrait)
class Controller {
public that = (this as unknown) as Controller & GetImageTrait;
public foo() {
this.that.getImage();
}
}
// ----------------
const controller = new Controller();
console.log('should log "GetImageTrait.getImage"');
controller.foo();
// 2. Function decorator usage for Intellisense
console.log('\n\n======= EXAMPLE 2');
const Controller2 = Use(
GetImageTrait,
ComputeTrait,
)(
class Controller2 {
public foo(this: Controller2 & GetImageTrait) {
this.getImage();
}
},
);
// ----------------
const controller2 = new Controller2();
console.log('should log "GetImageTrait.getImage"');
controller2.foo();
// 3 "as" & "insteadof" trait rules
console.log('\n\n======= EXAMPLE 3');
@Use(GetImageTrait, ComputeTrait, {
as: {
// can use the helper method as selector
// scope is not handled yet
[traitSelector(GetImageTrait, 'INSTANCE', true)]: 'protected III',
'GetImageTrait::S2': 'S3',
},
insteadOf: {
// or do the selector ourselves (only in non-obfuscated code)
'ComputeTrait.getImage': [GetImageTrait],
},
})
class Controller3 {}
// ----------------
const controller3: any = new Controller3();
console.log('should log undefined');
console.log((Controller3 as any).INSTANCE); // should log undefined
console.log('\n--------');
console.log('should log "toto"');
console.log((Controller3 as any).III); // should log "toto"
console.log('\n--------');
console.log('should log "ComputeTrait.getImage"');
controller3.getImage(); // should log "ComputeTrait.getImage"
console.log('\n--------');
console.log('should log "Static2"');
console.log((Controller3 as any).S3); // should log "Static2"