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

Angular Typed Forms:含额外字段的FormGroup无法赋值给基类型输入的问题

类型表单子类型兼容问题

我制作了一个基础示例来展示需求:

现有以下两种类型:

type BaseType = FormGroup<{
  user: FormControl<string>;
}>;

type SomeOtherType = FormGroup<{
  user: FormControl<string>;
  amount: FormControl<number>;
}>;

由于SomeOtherType满足BaseType的契约,我希望能将其传递给类型为BaseType的组件输入。

常规尝试会得到看似反向的错误:

Type 'SomeOtherType' is not assignable to type 'BaseType'.
Property 'amount' is missing in type '{ user: FormControl<string>; }' but required in type '{ user: FormControl<string>; amount: FormControl<number>; }'.

使用输入转换可以绕过所有限制:

@Input({ required: true, transform: (value: FormGroup): BaseType => value })
form!: BaseType;

但这种方式会允许任意FormGroup传入,而我希望仅限制为匹配基类型的对象。

补充背景:这是已完成产品的迁移工作,需要从全量非类型表单(untyped forms)迁移至新的类型表单。非类型表单下相关组件依赖表单控件子集的功能完全正常,希望保留该功能同时使用新的类型特性。


内容的提问来源于stack exchange,提问作者JWrightII

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:10:20