属性“filteredOptions”没有初始值设定项,并且未在构造函数中明确分配

时间:2021-02-22 12:32:30

标签: javascript node.js angular observable initializer

在我的 Angular 应用程序中,我有一个组件:

  filteredOptions: Observable<string[]>;

以下行给出错误:

Property 'filteredOptions' has no initializer and is not definitely assigned in the constructor.

28   filteredOptions: Observable<string[]>;

1 个答案:

答案 0 :(得分:3)

这是因为 typescript 2.7.2 包含一个严格的类检查,所有属性都应该在构造函数中声明。因此,要解决此问题,您可以:

  • 只需添加一个爆炸符号 (!),例如:name!:string;
  • "strictPropertyInitialization": false 添加到您的编译器选项中。
  • 使用filteredOptions: Observable<string[]> | undefined;
  • 使用filteredOptions?: Observable<string[]>

更多详情:

  • name!:string; : 编译器相信我,我保证它不会是未定义的(可能导致不可预测的行为)
  • "strictPropertyInitialization": false:请编译器在任何地方停止您的严格检查
  • 最后两个解决方案:编译器,filteredOptions 可能有也可能没有值。在这种情况下,您有责任在您的案例中处理未定义的值(在您的 HTML 模板中使用 ?.nullundefined 检查...等)