Search code examples
angulartypescriptangular-forms

Typed forms, extending common controls


export interface CommonControls {
  selected: FormControl<boolean>;
}

export interface FirstFormControls extends CommonControls {
  name: FormControl<string>;
  price: FormControl<string>;
}

export interface SecondFormControls extends CommonControls {
  ordering: FormControl<number>;
  type: FormControl<string>;
  description: FormControl<string>;
}

export type BaseFormGroup<T extends CommonControls> = FormGroup<T>;

Why can't I extend specific controls with common controls and use them in a type? Theres an error at FormGroup<T> saying

Type T does not satisfy the constraint
{ [K in keyof T]: AbstractControl<any, any>; }

I have seen suggestions around the web where they suggest to use:

export interface CommonControls {
  selected: FormControl<boolean>;
  [key: string]: AbstractControl<any, any>;
}

But that lets you add all kinds of controls to the FormGroup and that defeats the purpose of a strongly typed form.

Any advice?


Solution

  • Shouldn't it be where the property(key) belongs to one of the keys of CommonControls and the value is an AbstractControl.

    FormControl, FormGroup and FormArray inherit AbstractControl and it is the base type of the form controls.

    export interface CommonControls {
      selected: FormControl<boolean>;
    }
    
    export interface FirstFormControls extends CommonControls {
      name: FormControl<string>;
      price: FormControl<string>;
    }
    
    export interface SecondFormControls extends CommonControls {
      ordering: FormControl<number>;
      type: FormControl<string>;
      description: FormControl<string>;
    }
    
    export type BaseFormGroup<T extends CommonControls> = FormGroup<{
      [K in keyof T]: AbstractControl<any, any>;
    }>;