← 中文资源

简体中文版本

strictPropertyInitialization 守住字段初始化

类字段要么行内初始化、要么在构造函数里赋值、要么显式可选,否则 strict 编译直接报 TS2564:不会等到运行期才读出 undefined 状态。

阅读英文原文

运行结果

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

queue is empty: true
retries: 3
started: true
last error: none

实现说明

活动部件是类 JobRunner。 runner 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 演示输出是带标签的(queue is empty:、retries:、started:),每个操作都会留下自己的一行标注。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件的状态由几个模块级绑定持有:runner。

核心语句

const runner = new JobRunner(3);
this.maxRetries = maxRetries;
readonly maxRetries: number;

代码示例

class JobRunner {
  // Inline initializer satisfies the check
  queue: string[] = [];

  // Constructor assignment satisfies the check
  readonly maxRetries: number;
  readonly startedAt: Date;

  // Optional fields opt out: they may legitimately stay undefined
  lastError?: Error;

  constructor(maxRetries: number) {
    this.maxRetries = maxRetries;
    this.startedAt = new Date();
  }
}

// Without an initializer this fails to compile under strict
// (TS2564: property 'name' has no initializer and is not
// definitely assigned in the constructor):
// class Broken {
//   name: string;
// }

const runner = new JobRunner(3);
console.log('queue is empty:', runner.queue.length === 0);
console.log('retries:', runner.maxRetries);
console.log('started:', runner.startedAt instanceof Date);
console.log('last error:', runner.lastError ?? 'none');