如果字段在构造函数中使用前未定义,则添加警告

Add warning if field is undefined before use in constructor

我有这个代码:

  @Input() myUuid;
  private dcs: HistoryService;

  constructor(private hsf: HistoryServiceFactory) {
    console.log('my uuid:', this.myUuid.toString());
  }

据我所知,TypeScript 不会在这里给出警告:

但是 myUuid 应该始终是未定义的,因为它只能保证在 ngOnInit() 被触发后被初始化。 TS有没有可能知道这一点并显示(编译)警告?

将 TypeScript 更新到最新版本。 2.7 引入了这个功能:检查明确的分配。

这记录在 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html

具体来说:

TypeScript 2.7 introduces a new flag called --strictPropertyInitialization. This flag performs checks to ensure that each instance property of a class gets initialized in the constructor body, or by a property initializer. For example

确保您正在使用 --strict

请注意,如果您希望在构建后保留未初始化的属性,您现在需要将它们标记为可选 (property?)。在这种情况下,这始终是一个很好的做法,但现在已强制执行。