generated from garronej/ts-ci
-
Notifications
You must be signed in to change notification settings - Fork 6
/
overwriteReadonlyProp.ts
52 lines (44 loc) 路 1.36 KB
/
overwriteReadonlyProp.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
/* eslint-disable no-empty */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { assert } from "../assert.ts";
import { is } from "../is.ts";
/**
* Assign a value to a property even if the object is freezed or if the property is not writable
* Throw if the assignation fail ( for example if the property is non configurable write: false )
* */
export const overwriteReadonlyProp = <T extends { [key: string]: any }, K extends keyof T>(
obj: T,
propertyName: K,
value: T[K],
): T[K] => {
try {
obj[propertyName] = value;
} catch {}
if (obj[propertyName] === value) {
return value;
}
let errorDefineProperty: Error | undefined = undefined;
const propertyDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(
obj,
propertyName,
) || {
"enumerable": true,
"configurable": true,
};
if (!!propertyDescriptor.get) {
throw new Error(`Probably a wrong ides to overwrite ${propertyName} getter`);
}
try {
Object.defineProperty(obj, propertyName, {
...propertyDescriptor,
value,
});
} catch (error) {
assert(is<Error>(error));
errorDefineProperty = error;
}
if (obj[propertyName] !== value) {
throw errorDefineProperty || new Error("Can't assign");
}
return value;
};