Angular 14 valuechanges type error in visual studio code

Viewed 29

I'm trying to use the new typed reactive forms from angular 14. And getting this error when upgrading angular from 12 -> 14.

I'm using typescript strict mode = true.

Im getting type error from visual studio code:

Argument of type 'string | { validators: ((control: AbstractControl<any, any>) => ValidationErrors | null)[]; }' is not assignable to parameter of type 'string'.
  Type '{ validators: ((control: AbstractControl<any, any>) => ValidationErrors | null)[]; }' is not assignable to type 'string'.ts(2345)

Creating a form with FormBuilder like this

  form = this.fb.nonNullable.group({
    country: ["", { validators: [Validators.required] }],
    area: ["", { validators: [Validators.required] }]
  });

Subscribing to valuechanges:

this.form.get('country')?.valueChanges.subscribe(value => {
 checkCountry(value): <------ Gets type error here because checkCountry requires string in
});

How do i get rid of this problem i dont want to disable strict mode. Is there any better of doing things.

1 Answers

The type emitted by valueChanges is a union type, thus you need a type guard to be sure you're handling a string:

this.form.get('country')?.valueChanges.subscribe(value => {
 if (typeof value === 'string') {
   checkCountry(value);
 }
});
Related