You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 16:为FormControl数组类型赋值同类型数组报错求助

解决Angular 16中FormControl赋值类型不匹配问题

问题原因

你声明selectedInterests这个FormControl时,没有显式指定泛型类型,TypeScript自动推断其类型为never[],导致赋值Interest[]类型的数组时出现类型不兼容错误。

解决步骤

  1. 给FormControl指定泛型类型
    修改profileData中selectedInterests的定义,明确指定其类型为Interest[]:
profileData = new FormGroup({
  // 其他Form Controls...
  selectedInterests: new FormControl<Interest[]>([], Validators.required)
});
  1. 修正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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:35:24