FormControl type angular Abscract type typescript

Viewed 731

I am trying to make tslint proper return type, and have something like this

 get formControls(): any {
    return this.form.controls;
  }

It returns the error Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type.

In previous question FormControl type angular typescript I got answer to my question to make it like this

 get formControls(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

It is now OK, but then I have problems with other functions inside component, because I have more get like this

  get addressFormControls(): any {
    return this.formControls.address.controls;
  }

  get addressFormGroup(): any {
    return this.formControls.address;
  }

Now I got another error Property 'controls' does not exist on type 'AbstractControl'

Here is my final code, can somebody help me to write proper return type

  get formControls(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  get addressFormControls(): any {
    return this.formControls.address.controls;
  }

  get addressFormGroup(): any {
    return this.formControls.address;
  }

Thanks in advance

1 Answers

It is obvious to get an error with that.

AbstractControl is the base class that FormGroup FormArray and FormControl extends.

FormGroup and FormArray defines control which is not available in FormControl and AbstractControl.

As per angular definitions, if say form is of type FormArray then formControls() must return AbstractControl[]

get formControls(): AbstractControl[] {
  return this.form.controls;
}

However if form is a FormGroup then the return type is fine as you mentioned

get formControls(): { [key: string]: AbstractControl } {
  return this.form.controls;
}

But since AbstractControl does not defines controls we can manually typecast it to FormGroup. So in this case this would solve the problem.

get addressFormControls(): { [key: string]: AbstractControl } {
  return (this.formControls.address as FormGroup).controls;
}

get addressFormGroup(): FormGroup {
  return this.formControls.address as FormGroup;
}

Update: I would suggest a refactor as

get addressFormControls(): { [key: string]: AbstractControl } {
  return this.addressFormGroup.controls;
}
Related