Created
January 7, 2026 14:31
-
-
Save mimshins/f3b3377bc205cc76f1735dc3224bd5ee to your computer and use it in GitHub Desktop.
Define a lazily evaluated property on arbitary objects.
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
| type ModifiedObject< | |
| TObject extends Record<string, unknown>, | |
| TPropertyName extends string, | |
| TPropertyValue, | |
| > = TObject & { | |
| [K in TPropertyName]: TPropertyValue; | |
| }; | |
| export const defineLazyProperty = < | |
| TObject extends Record<string, unknown>, | |
| TPropertyName extends string, | |
| TPropertyValue, | |
| >( | |
| object: TObject, | |
| propertyName: TPropertyName, | |
| valueGetter: () => TPropertyValue, | |
| ): ModifiedObject<TObject, TPropertyName, TPropertyValue> => { | |
| const define = (value: TPropertyValue) => | |
| Object.defineProperty(object, propertyName, { | |
| value, | |
| enumerable: true, | |
| writable: true, | |
| }); | |
| Object.defineProperty(object, propertyName, { | |
| configurable: true, | |
| enumerable: true, | |
| get(): TPropertyValue { | |
| const result = valueGetter(); | |
| define(result); | |
| return result; | |
| }, | |
| set(value: TPropertyValue) { | |
| define(value); | |
| }, | |
| }); | |
| return object as ModifiedObject<TObject, TPropertyName, TPropertyValue>; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment