Skip to content

Instantly share code, notes, and snippets.

@rickytan
Last active April 17, 2024 16:24
Show Gist options
  • Save rickytan/83a68ec5306b0d658d8f633c6d2e4f65 to your computer and use it in GitHub Desktop.
Save rickytan/83a68ec5306b0d658d8f633c6d2e4f65 to your computer and use it in GitHub Desktop.
TypeScript @ Lazy annotation
function Lazy<T>(target: Object, propertyKey: string | symbol, {
get:initializer,
enumerable,
configurable,
set:setter
}: TypedPropertyDescriptor<T> = {}): TypedPropertyDescriptor<T> {
const {constructor} = target;
if (setter) {
throw `@Lazy can't be annotated with get ${propertyKey.toString()}() existing a setter on ${constructor.name} class!`;
}
return {
get() {
const value = initializer.call(this)
Object.defineProperty(this, propertyKey, {
enumerable: enumerable,
configurable: configurable,
get() {
return value
}
});
return value;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment