Angular 16:为FormControl数组类型赋值同类型数组报错求助
解决Angular 16中FormControl赋值类型不匹配问题
问题原因
你声明selectedInterests这个FormControl时,没有显式指定泛型类型,TypeScript自动推断其类型为never[],导致赋值Interest[]类型的数组时出现类型不兼容错误。
解决步骤
- 给FormControl指定泛型类型
修改profileData中selectedInterests的定义,明确指定其类型为Interest[]:
profileData = new FormGroup({ // 其他Form Controls... selectedInterests: new FormControl<Interest[]>([], Validators.required) });
- 修正HTML中的拼写错误
注意到你HTML里的mat-error部分,profileData.controls.selectedInterest少了末尾的s,应该改为selectedInterests,否则验证错误提示无法正常触发:
<mat-error *ngIf="profileData.controls.selectedInterests.hasError('required')"> {{ 'PROFILE.VALID.INTEREST' | translate }} </mat-error>
补充说明
通过显式指定FormControl的泛型类型,TypeScript就能正确识别selectedInterests的预期类型,后续赋值loadedProfile.interests(类型为Interest[])时就不会再出现类型错误。
内容的提问来源于stack exchange,提问作者Alfredo Marin
相关产品推荐
相关产品推荐

