首页 > 解决方案 > (control: AbstractControl) :

问题描述

Here a snippet of code extract from https://angular.io/guide/form-validation#custom-validators

/** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
   return (control: AbstractControl): {[key: string]: any} => {
       const forbidden = nameRe.test(control.value);
       return forbidden ? {'forbiddenName': {value: control.value}} : null;
  };
}

What is happening at the third line :

 return (control: AbstractControl): () => {}

Is it typing what the lambda function will return ? forbiddenNameValidator is supposed to return a ValidatorFn, should ValidatorFn be understood as ValidatorFonction ?

标签: javascriptangulartypescripttypescasting

解决方案


如果您研究ValidatorFn接口的定义,它具有以下模式 -

interface ValidatorFn {
  (c: AbstractControl): ValidationErrors | null
}

这意味着您可以返回任何接受类型参数AbstractControl并返回类型ValidationErrors(实际上是类型别名)或null.

这是 的定义ValidationErrors,它具有以下索引签名

type ValidationErrors = {
    [key: string]: any;
};

所以你下面的例子

return (control: AbstractControl): {[key: string]: any} => { 
 // other code 
 return forbidden ? {'forbiddenName': {value: control.value}} : null; // check this line it's corresponds to ValidationErrors | null
}

ValidatorFn实际上返回一个与接口模式兼容的相同签名的函数。

(control: AbstractControl): {[key: string]: any} => 
       {
         return forbidden ? {'forbiddenName': {value: control.value}} : null; 
       }

检查此链接以供参考:https ://angular.io/api/forms/ValidatorFn#call

所以函数背后的想法forbiddenNameValidator是返回一个与ValidatorFn接口属性具有相同签名的函数


推荐阅读