Skip to content

Instantly share code, notes, and snippets.

@imnemo
Forked from kingfolk/lazy.ts
Created August 26, 2020 09:57
Show Gist options
  • Select an option

  • Save imnemo/de3473c5ecd3192c53b335a8a939a0e8 to your computer and use it in GitHub Desktop.

Select an option

Save imnemo/de3473c5ecd3192c53b335a8a939a0e8 to your computer and use it in GitHub Desktop.
typescript lazy decorator
function Lazy<T>(initializer: () => T) {
// the return type of a property decorator function must be either 'void' or 'any'
return function lazy(target, name): any {
function set(value, that = this) {
Object.defineProperty(that, name, {
enumerable: true,
configurable: false,
writable: false,
value: value,
});
}
return {
get() {
const value = initializer.call(this);
set(value, this);
return value;
},
set,
};
};
}
class Counter {
static id = 0;
a;
constructor(a = Counter.id ++) {
this.a = a;
}
}
class Host {
// not work in ts-node env. TypeError: Cannot redefine property: c.
// @Lazy(() => new Counter(1000))
// static c: Counter;
@Lazy(() => new Counter)
counter: Counter;
}
const host = new Host();
console.log('host.counter', host.counter);
// console.log('host.c', Host.c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment