-
Notifications
You must be signed in to change notification settings - Fork 1
/
coerce.ts
30 lines (30 loc) · 876 Bytes
/
coerce.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
/**
* Coerce decorator
*/
export function coerce<
T extends { [key in P]: O } = any,
P extends string | symbol = string | symbol,
I = any,
O = any
>(
coerceFn: (value: I, self: T) => O,
afterFn?: (value: O, self: T) => void
): PropertyDecorator {
return function(target: T, propertyKey: P) {
const _key = Symbol();
target[_key] = target[propertyKey];
Object.defineProperty(target, propertyKey, {
get: function() {
return this[_key];
},
set: afterFn
? function(v: I) {
this[_key] = coerceFn.call(this, v, this);
afterFn.call(this, this[_key], this);
}
: function(v: I) {
this[_key] = coerceFn.call(this, v, this);
}
});
};
}