angular - 必需的 Input() 参数仍然发出 "has no initializer"错误

标签 angular typescript

我喜欢 TypeScript 的所有新的 null 安全功能,但有时我不确定如何处理某些情况。
我经常遇到的一种情况是:

假设我有一个带有 @Input() 参数的组件。
该参数是必需的(在 Angular 16 中引入),例如:

@Input({ required: true }) myInput1: string;

但是, typescript 在这里发出错误:

Property 'myInput1' has no initializer and is not definitely assigned in the constructor.ts(2564)

我认为这个错误是不必要的,因为我将强制组件的调用者传递输入参数。这是有原因的。

但是,没有一个解决方案是我喜欢的。

  • 禁用 strictPropertyInitialization 并不好,因为我 还是想要空安全。
  • 通过 ?-Operator 将属性标记为可为空也不好,因为该属性不可为空。必须设置它。这是必需的。
  • 由于同样的原因,将 undefined 添加到可能的类型中也不好。
  • 用默认值初始化该值也不好,因为这个值是错误的。不过,这仍然是我的最爱。

还有其他可以推荐的解决方案吗

最佳答案

实现此目的的方法是使用非空断言运算符 !

@Input({ required: true }) myInput1!: string;

关于angular - 必需的 Input() 参数仍然发出 "has no initializer"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77470424/

相关文章:

javascript - 如何手动注册到 Angular 中的内部组件事件?

constructor - TypeScript 类成员速记错误?

typescript - 如何在 tsconfig 中使用单个模块的路径?

typescript - 通过 NSwag 代码生成器(angular 2 typescript )下载文件的正确方法是什么

Angular 。如何使用 Location.back() 使 CanDeactivate 正常工作

angular - Angular 7 中的中间件?

javascript - 如何模拟进行 AJAX 调用的方法?

javascript - "module": "esnext" in tsconfig. json没有去掉Dynamic Lazy load模块报错

node.js - TypeScript 内存错误未终止 Docker 构建

typescript - protected 属性的通用 getter 和 setter