1

I am working on Angular 14, Typescript 4.7, Angualr/forms: 14.3.0.

Below is a minimum error reproducible code snippet.

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;
}

I am getting the following error:

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.

And TypeScript also requires me to have type assertion as string, in the code.

How can I resolve the error and not use the type assertion.

1 Answer 1

1

The form control, is of type string | null, so you should set the interface, so accept both string | null.

interface IForm {
  name: FormControl<string | null>;
}

Stackblitz Demo


If you are 100% certain, that the form control is not nullable and will always contain a string, then you can use `` to make sure the value is not null.

private buildForm(): FormGroup<IForm> {
  const form: FormGroup<IForm> = this.formBuilder.group({
    name: this.formBuilder.nonNullable.control('Sample Name', Validators.required),
  });
  return form as FormGroup<IForm>;
}

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.