Skip to content

AsyncValidatorFn can be passed as ValidatorFn to FormControl without warning #48676

@JeanMeche

Description

@JeanMeche

Which @angular/* package(s) are relevant/related to the feature request?

forms

Description

Today the one of the 5 constructors of FormControl looks like this :

  new<T = any>(
      value: FormControlState<T>|T,
      validatorOrOpts?: ValidatorFn|ValidatorFn[]|FormControlOptions|null,
      asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormControl<T|null>;

The problem is that the compilator won't mind when passing an AsyncValidatorFn as 2nd parameter but the validation will always error since AsyncValidatorFn doesn't return null.

const foo: AsyncValidatorFn = (): Observable<{} | null> => {
  return of({});
};
const ctrl = new FormControl(3, foo); // compiler OK but validation won't work. 

The root case is that ValidatorFn returns a very loose type ValidationErrors : { [key: string]: any}. Observable<any> or Promise<any> are valid ValidationErrors.

Repro on Stackblitz

Proposed solution

Improve the typings of ValidationErrors or somehow make AsyncValidatorFn & ValidatorFn incompatible for example: with type ValidatorFn = (control: AbstractControl) => (ValidationErrors & { then?: never, subscribe?: never}) | null;

Demo on playground

Alternatives considered

Devs should be better at reading the apis :(

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions