Created
July 24, 2023 08:29
-
-
Save danmichaelo/708989a7db51b7d332853e0db3b7ecd0 to your computer and use it in GitHub Desktop.
Lazy-loaded object in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const lazyLoaded = <Data extends object>(loadData: () => Data) => { | |
let data: Data | undefined = undefined; | |
const isDataKey = ( | |
obj: Data, | |
key: string | symbol | number | |
): key is keyof Data => key in obj; | |
return new Proxy<Data>({} as Data, { | |
get: (_target, prop) => { | |
if (typeof data === "undefined") { | |
data = loadData(); | |
} | |
if (isDataKey(data, prop)) { | |
return data[prop]; | |
} | |
}, | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment