Home > front end >  Type '(control: AbstractControl) => Observable<unknown>' is not assignable to typ
Type '(control: AbstractControl) => Observable<unknown>' is not assignable to typ

Time:06-13

I am trying to get working an async email validator and this code is from a tutorial but I think the versions changed and it complains and honestly I don't understand this error.

validateEmailNotTaken(): AsyncValidatorFn {
return control => {
  return timer(500).pipe(
    switchMap(() => {
      if (!control.value) {
        return of(null);
      }
      return this.accountService.checkEmailExists(control.value).pipe(
        map(res => {
          return res ? { emailExists: true } : null;
        })
      );
    })
  );
};

error:

Type '(control: AbstractControl) => Observable<unknown>' is not assignable to type 
 'AsyncValidatorFn'.
  Type 'Observable<unknown>' is not assignable to type 'Promise<ValidationErrors | null> | Observable<ValidationErrors | null>'.
    Type 'Observable<unknown>' is not assignable to type 'Observable<ValidationErrors | null>'.
      Type 'unknown' is not assignable to type 'ValidationErrors | null'.  

First of all can someone explain me how to read this error?

So I am assuming all errors are related to first return but because I didn't specified a type in switchMap or at the end it throws this error and I don't know what types it needs.

Thank you

Edit: So I figured out that this error comes from the empty paramter switchMap but I don't know what to provide inside for a parameter

Edit2: If I remove the last return then I get a different error inside the switchMap block:

Argument of type '() => Observable<null> | undefined' is not assignable to parameter of type '(value: 0, index: number) => ObservableInput<any>'.
  Type 'Observable<null> | undefined' is not assignable to type 'ObservableInput<any>'.
    Type 'undefined' is not assignable to type 'ObservableInput<any>'.

Edit3: per comment

  email: new FormControl('', [
    Validators.required,
    Validators.pattern('^[\\w-\\.] @([\\w-] \\.) [\\w-]{2,4}$'),
  ], [this.validateEmailNotTaken()]),

CodePudding user response:

Try adding stricter typing - it may just be that the types aren't explicit enough

validateEmailNotTaken(): AsyncValidatorFn {
   return (control: AbstractControl): Observable<ValidationErrors | null> => {
     ...

  • Related