-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathproxyObject.ts
More file actions
35 lines (33 loc) · 918 Bytes
/
proxyObject.ts
File metadata and controls
35 lines (33 loc) · 918 Bytes
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
/**
* Proxy object if environment supported
*/
export default function proxyObject<
Obj extends object,
ExtendObj extends object,
>(obj: Obj, extendProps: ExtendObj): Obj & ExtendObj {
if (typeof Proxy !== 'undefined' && obj) {
return new Proxy(obj, {
get(target, prop) {
if (extendProps[prop]) {
return extendProps[prop];
}
// Proxy origin property
const originProp = (target as any)[prop];
return typeof originProp === 'function'
? originProp.bind(target)
: originProp;
},
set(target, prop, v) {
let value = v;
if (typeof prop === 'string' && ['value'].includes(prop)) {
if (typeof value !== 'string') {
value = '' + value;
}
target[prop] = value;
return true;
}
},
}) as Obj & ExtendObj;
}
return obj as Obj & ExtendObj;
}