1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Type narrowing is lost when accessing nested form controls in Angular generic reactive forms

Discussão em 'Angular' iniciado por lldan, Setembro 16, 2025.

  1. lldan

    lldan Guest

    I found some strange behavior of the types in the form

    interface RootForm {
    children: FormGroup<ChildrenForm>;
    }

    interface ChildrenForm {
    field: FormControl<string>;
    }

    @Injectable()
    class RootService<F extends RootForm> {
    private fb = inject(FormBuilder);

    public form = this.fb.nonNullable.array<FormGroup<F>>([]);
    }


    TYPESCRIPT ERROR:
    TS2344: Type F does not satisfy the constraint
    { [K in keyof F]: AbstractControl<any, any>; }
    Type QuestionForm is not assignable to type
    { [K in keyof F]: AbstractControl<any, any>; }


    ok, i found a solution to fix this

    interface RootForm extends Record<string, AbstractControl> {
    children: FormGroup<ChildrenForm>;
    }


    BUT this creates another problem:

    @Injectable()
    class RootService<F extends RootForm> {
    private fb = inject(FormBuilder);

    public form = this.fb.nonNullable.array<FormGroup<F>>([]);

    public childrenForm = computed(() => this.form.at(0).controls.children);
    }


    Type of childrenForm is AbstractControl<any, any> | FormGroup<ChildrenForm>, although I just want to see it there FormGroup<ChildrenForm>

    Of course, the type can be cast, but it is also necessary to take into account that the form can be undefined. Plus, if the form is complex and you often have to create such computed, you need to cast the type each time and complicate the code

    Continue reading...

Compartilhe esta Página