-
Notifications
You must be signed in to change notification settings - Fork 2
/
private-fields-on-plain-objects.ts
58 lines (45 loc) · 1.29 KB
/
private-fields-on-plain-objects.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
// Utilities for creating private fields on plain objects. As is noted in the
// proposal (tc39/proposal-class-fields), private fields are really syntax sugar
// for WeakMaps, so this is allowed.
const ReturnInput = function <T>(object: T): T {
return object
} as unknown as new <T>(object: T) => T
function createPrivateField<Target extends object, Field>() {
// @ts-ignore
class PrivateField extends ReturnInput<Target> {
#field!: Field
constructor(object: Target, field: Field) {
super(object)
this.#field = field
}
static get(object: Target): Field {
return (object as any).#field
}
static set(object: Target, value: Field): Target {
if (!(#field in object)) {
new PrivateField(object, value)
}
;(object as any).#field = value
return object
}
static has(object: object): object is Target {
return #field in object
}
}
return {
get(object: Target): Field {
return PrivateField.get(object)
},
set(object: Target, value: Field): Target {
return PrivateField.set(object, value)
},
has(object: Target) {
return PrivateField.has(object)
},
}
}
const name = createPrivateField<{}, string>()
const Zachary = {}
name.set(Zachary, "Zachary")
name.get(Zachary)
export {}