javascript - (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 ?
解决方案
如果您研究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
接口属性具有相同签名的函数
推荐阅读
- vim - 是什么导致 vim exec 所需的 `\` 数量不对称?
- ruby-on-rails - 错误修复。如何运行回调并保存但不进行验证?
- r - 在ggplot2中右对齐旋转轴标题
- javascript - 在安全性方面 map over for 循环的好处
- .net - 如何使用面板上的图形类绘制多色文本?
- c++ - C 和 C++ 中的二维数组差异
- java - 如何快速初始化 char 二维数组?
- r - 如何将数据框对象从 renderUI 传递到 eventReactive?
- javascript - ReactJS - 单击时更改属性值
- python - 如何根据给定列表使用python将数据添加到Excel工作表中的特定行/列?