13

As of Angular 14, reactive forms are strictly typed by default (Typed Forms). This is great. I have implemented a simple login form like below

  form = this.fb.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required]],
    rememberMe: [true]
  });
  submit() {
    this.authenticationService.login(this.form.value).subscribe();

And in the service I have

login(data: { username: string; password: string; rememberMe: boolean }): Observable<any> {
  // Logic to login here
}

Typescript infers the type of form to be

  form: FormGroup<{username: FormControl<string>, password: FormControl<string>, rememberMe: FormControl<boolean>}>

which looks good. The problem arises with this.form.value that has a type Partial<{ username: string; password: string; rememberMe: boolean; }>. This causes typescript to throw an error

Argument of type 'Partial<{ username: string; password: string; rememberMe: boolean; }>' is not assignable to parameter of type '{ username: string; password: string; rememberMe: boolean; }'.   Property 'username' is optional in type 'Partial<{ username: string; password: string; rememberMe: boolean; }>' but required in type '{ username: string; password: string; rememberMe: boolean; }'.

Is there a way while declaring the formgroup to indicate that the field will be available in the formgroup value. Currently I am typecasting like below

this.form.value as {username: string; rememberMe: boolean; password: string}

The above works but will it have to be typecast for all forms?

Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74

1 Answers1

16

It is Partial because some controls can be disabled (and potential undefined).

To get all values, use this.form.getRawValue().

Eugene
  • 1,242
  • 1
  • 10
  • 15
  • Thanks for your answer though as per my question, I am looking for a way to specify the type not get all values including disabled properties – Owen Kelvin Sep 17 '22 at 07:24
  • 1
    Hm, I think you can't resolve it only by types "which controls are enabled", like your _working_ example, which assumes that all fields are enabled, but in reality it may not be so. Btw, that typecasting can be replaced with `as Required` – Eugene Sep 17 '22 at 10:02
  • `Required` looks neat, will try it out thanks – Owen Kelvin Sep 17 '22 at 11:15