我喜欢 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/