FormControl 类型 angular 抽象类型打字稿 [英] FormControl type angular Abscract type typescript
问题描述
我正在尝试使 tslint 成为正确的返回类型,并且有这样的东西
I am trying to make tslint proper return type, and have something like this
get formControls(): any {
return this.form.controls;
}
它返回错误 'any' 的类型声明失去了类型安全性.考虑用更精确的类型替换它.
在上一个问题中FormControl 类型角度打字稿我得到了我的问题的答案,使它像这样
In previous question FormControl type angular typescript I got answer to my question to make it like this
get formControls(): { [key: string]: AbstractControl } {
return this.form.controls;
}
现在可以了,但是组件内部的其他功能出现问题,因为我有更多这样的功能
It is now OK, but then I have problems with other functions inside component, because I have more get like this
get addressFormControls(): any {
return this.formControls.address.controls;
}
get addressFormGroup(): any {
return this.formControls.address;
}
现在我遇到另一个错误属性控件"在类型AbstractControl"上不存在
这是我的最终代码,谁能帮我编写正确的返回类型
Here is my final code, can somebody help me to write proper return type
get formControls(): { [key: string]: AbstractControl } {
return this.form.controls;
}
get addressFormControls(): any {
return this.formControls.address.controls;
}
get addressFormGroup(): any {
return this.formControls.address;
}
提前致谢
推荐答案
很明显会出现错误.
AbstractControl
是 FormGroup
FormArray
和 FormControl
扩展的基类.
AbstractControl
is the base class thatFormGroup
FormArray
andFormControl
extends.
FormGroup
和 FormArray
定义了 FormControl
和 AbstractControl
中没有的 control
>.
FormGroup
and FormArray
defines control
which is not available in FormControl
and AbstractControl
.
根据角度定义,如果说 form
是 FormArray
类型,那么 formControls()
必须返回 AbstractControl[]代码>
As per angular definitions, if say form
is of type FormArray
then formControls()
must return AbstractControl[]
get formControls(): AbstractControl[] {
return this.form.controls;
}
但是,如果 form
是 FormGroup
那么返回类型就可以了,正如您提到的
However if form
is a FormGroup
then the return type is fine as you mentioned
get formControls(): { [key: string]: AbstractControl } {
return this.form.controls;
}
但是由于AbstractControl
没有定义controls
,我们可以手动将其类型转换为FormGroup
.所以在这种情况下,这将解决问题.
But since AbstractControl
does not defines controls
we can manually typecast it to FormGroup
. So in this case this would solve the problem.
get addressFormControls(): { [key: string]: AbstractControl } {
return (this.formControls.address as FormGroup).controls;
}
get addressFormGroup(): FormGroup {
return this.formControls.address as FormGroup;
}
更新:我建议重构为
get addressFormControls(): { [key: string]: AbstractControl } {
return this.addressFormGroup.controls;
}
这篇关于FormControl 类型 angular 抽象类型打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!