我正在开发 Angular 14、Typescript 4.7、Angualr/forms:14.3.0。
下面是最小错误可重现的代码片段。
import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-learn',
templateUrl: './learn.component.html',
})
export class LearnComponent {
constructor(private formBuilder: FormBuilder) { }
public form!: FormGroup<IForm>
private buildForm(): FormGroup<IForm> {
const form: FormGroup<IForm> = this.formBuilder.group({
name: new FormControl<string>("Sample Name", Validators.required),
});
return form as FormGroup<IForm>;
}
private createContractModel(): IData {
const formValues = this.form.value;
const contract: IData = {
name: formValues.name as string,
}
return contract;
}
}
interface IForm {
name: FormControl<string>;
}
interface IData {
name: string;
}
我收到以下错误:
Type 'FormGroup<{ name: FormControl<string | null>; }>' is not assignable to type 'FormGroup<IForm>'.
Types of property 'controls' are incompatible.
Type '{ name: FormControl<string | null>; }' is not assignable to type 'IForm'. ts(2322)
Error (TS2322)
FormGroup<{ name: FormControl<string | null> }>' is not assignable to type FormGroup<IForm>.
Types of property controls are incompatible.
Type '{ name: FormControl<string | null> }' is not assignable to type IForm.
TypeScript 还要求我在代码中进行类型断言
as string
。
如何解决错误而不使用类型断言。
表单控件,类型为
string | null
,所以你应该设置界面,所以接受两个string | null
。
interface IForm {
name: FormControl<string | null>;
}