Definite Assignment Asserts Late Init
Use a definite assignment assertion for a map initialized in init(), then guard reads and writes until the cache is ready.
Code
class LazyCache {
// The definite assignment assertion promises init() runs before first use.
private store!: Map<string, string>;
private ready = false;
init(): void {
this.store = new Map<string, string>();
this.ready = true;
}
set(key: string, value: string): void {
if (!this.ready) {
throw new Error('call init() first');
}
this.store.set(key, value);
}
get(key: string): string | undefined {
return this.ready ? this.store.get(key) : undefined;
}
}
const cache = new LazyCache();
console.log('before init:', cache.get('mode'));
cache.init();
cache.set('mode', 'production');
console.log('after init:', cache.get('mode'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
before init: undefined
after init: productionHow it works
Definite Assignment Asserts Late Init is built around the class LazyCache.
When the guard condition holds, Error is thrown rather than a bogus value returned.
Module-level bindings hold the data — cache — with no function scope in between.
Points of care
- The guard
!this.readyshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The demo output is labeled (before init:, after init:), so each printed line maps back to the step that produced it.
Statements that matter
return this.ready ? this.store.get(key) : undefined;
this.store = new Map<string, string>();
throw new Error('call init() first');
Interactive Tools for This Topic
FAQ
- What happens if the preconditions do not hold?
- Validation comes first — `Error` marks the failure at `!this.ready`, before any partial work happens.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `cache`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.