← 中文资源

简体中文版本

明确赋值断言延迟初始化

用明确赋值断言声明稍后在 init() 中初始化的 Map,并在就绪前拦截读写,避免未初始化访问。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

before init: undefined
after init: production

实现说明

活动部件是类 LazyCache。 代码不会带着坏状态静默继续,守卫一命中就抛 Error。 顶层就这几处状态:cache。

使用要点

  • 守卫 !this.ready 一旦成立就走提前的 throw,把后续流程挡掉。
  • 演示输出是带标签的(before init:、after init:),每个操作都会留下自己的一行标注。

常见问题

前置条件不成立会发生什么?

校验先行——Error 标记失败(位于 !this.ready),不会先做一半再失败。

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件的状态由几个模块级绑定持有:cache。

核心语句

return this.ready ? this.store.get(key) : undefined;
this.store = new Map<string, string>();
throw new Error('call init() first');

代码示例

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'));