-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathdecorators.4.ts
40 lines (33 loc) · 1.1 KB
/
decorators.4.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
'use strict';
import "reflect-metadata";
namespace decorators {
// @ts-ignore
const formatMetadataKey = Symbol("format");
enum format {
toUpperCase,
toLowerCase,
toLocaleUpperCase,
toLocaleLowerCase
}
/**
* 当 @format("Hello, %s")被调用时,它添加一条这个属性的元数据,通过reflect-metadata库里的Reflect.metadata函数。
* 当 getFormat被调用时,它读取格式的元数据。
*/
class Greeter {
@Reflect.metadata(formatMetadataKey, format.toLocaleUpperCase)
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
let formatType = getFormat(this, "greeting");
return `${format[formatType]}: ${this.greeting[format[formatType] || 0]()}`;
}
}
function getFormat(target: any, propertyKey: string) {
console.log(target, propertyKey);
return Reflect.getMetadata(formatMetadataKey, target, propertyKey);
}
const greeter = new Greeter('Greeter');
console.log(greeter.greet());
}