-
-
Save imnemo/de3473c5ecd3192c53b335a8a939a0e8 to your computer and use it in GitHub Desktop.
typescript lazy decorator
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
| 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