Updated: 03 September 2023

1
interface Person {
2
name: string
3
}
4
5
type DB = Record<string, Person>
6
7
const db: DB = {
8
bob: {
9
name: 'Bob',
10
},
11
jeff: {
12
name: 'Jeff',
13
},
14
}
15
16
const alwaysDefinedHandler: ProxyHandler<DB> = {
17
get(target, prop, receiver) {
18
const user = db[prop as string]
19
20
if (!user) {
21
db[prop as string] = {
22
name: prop as string,
23
}
24
25
return db[prop as string]
26
}
27
28
return user
29
},
30
}
31
32
const insertIfNotFoundDb = new Proxy<DB>(db, alwaysDefinedHandler)
33
34
console.log(insertIfNotFoundDb.bob)
35
36
console.log(db)
37
38
// smith is not in the database, but the act of accessing it through a proxy will create the person
39
// based on the logic we have defined in the proxy
40
console.log(insertIfNotFoundDb.smith)
41
42
console.log(db)
43
44
// @ts-expect-error
45
console.log(insertIfNotFoundDb[new Date()])
46
47
console.log(db)