0

I want to understand the syntax of the following TypeScript function.

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn
{
  return (control: AbstractControl): {[key: string]: any} | null => {
                           const forbidden = nameRe.test(control.value);
                           return forbidden ? {'forbiddenName': {value: control.value}} : null;
                          };
}

Here: AbstractControl: https://angular.io/api/forms/AbstractControl

My understanding is:

  1. forbiddenNameValidator: name of the user defined function.

  2. nameRe: RegExp: Argument to function - forbiddenNameValidator.

  3. ValidatorFn: Return type of the function - forbiddenNameValidator.

From here: https://angular.io/api/forms/ValidatorFn

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

That documentation says that (control: AbstractControl): ValidationErrors | null is a function.

Which symbol here shows that it is a function? I had read that => symbol represents functions.

1 Answer 1

1

Which symbol here shows that it is a function? I had read that => symbol represents functions.

There's a few different ways to create function types. The one you see here only occurs if you're defining an interface, and want to specify that that interface is also callable. The syntax is to have the argument list on the left hand side wrapped in parentheses, then a colon, then the return value on the right hand side.

You can see more about this particular syntax here: https://www.typescriptlang.org/docs/handbook/interfaces.html#function-types

And other ways of doing functions here, including the => version you're familiar with: https://www.typescriptlang.org/docs/handbook/functions.html

How does control: AbstractControl receive the argument in the following part of that code?

These lines are merely creating and then returning the validator function. No control object exists yet. Eventually someone will call this new validator function, and it will be their responsibility to pass in an appropriate object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.