Updated: 03 September 2023
1interface Person {2 name: string3}4
5type DB = Record<string, Person>6
7const db: DB = {8 bob: {9 name: 'Bob',10 },11 jeff: {12 name: 'Jeff',13 },14}15
16const 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 user29 },30}31
32const insertIfNotFoundDb = new Proxy<DB>(db, alwaysDefinedHandler)33
34console.log(insertIfNotFoundDb.bob)35
36console.log(db)37
38// smith is not in the database, but the act of accessing it through a proxy will create the person39// based on the logic we have defined in the proxy40console.log(insertIfNotFoundDb.smith)41
42console.log(db)43
44// @ts-expect-error45console.log(insertIfNotFoundDb[new Date()])46
47console.log(db)