我正在更新一些遗留表单,使其类型更加强健,从而修复 eslint 错误。我不断遇到这样的问题:抽象控件上的
.value
运算符会引发 IDE 错误“在 any
值上访问 .value 不安全”。这违反了我的项目no-unsafe-member-access。例如:
// strong typing from the start
interface sampleForm {
account_1: FormControl<string>;
account_2: FormControl<string>;
};
// Form builder
this.myForm: sampleForm = this.formBuilder.group({
account_1: new FormControl<string|null>("placeholder", [Validators.maxLength(128),]),
accounte_2: new FormControl<string|null>("", [Validators.maxLength(128),]),
});
// the problem, "Unsafe assignment of an `any` value", "Unsafe member access .value on an `any` value."
const t = this.myForm.controls[`account_${1}].value;
我尝试过使用
controls.controlName.getRawValue()
、controls.get(controlName)
、controls.controlName.value as string
、let t = controls.controlName as AbstractControl; t = t.value as string;
都抛出相同的警告。
尝试:
const t = (this.myForm.controls[`account_${1}`] as FormControl<string>).value;
使用类型断言(this.myForm.controls[account_${1}] as FormControl),TypeScript 知道控件确实是 FormControl 类型,因此访问其 value 属性是安全的。