简体   繁体   中英

Angular 6 custom validation return type

I have this code in my project for custom validation but I am unable to understand what does: (group: FormGroup) => ValidationResult mean here?

I understand: (group: FormGroup) means return type but then what does => ValidationResult mean here?

static comparePasswords(passwordKey: string, confirmPasswordKey: string): (group: FormGroup) => ValidationResult {
    return (group: FormGroup): ValidationResult => {
      const password = group.controls[passwordKey];
      const confirmPassword = group.controls[confirmPasswordKey];
      if (password.value !== confirmPassword.value) {
        return { mismatchedPasswords: true };
      }
    };
  }

The full return type is (group: FormGroup) => ValidationResult . That is, the return type is a function that takes a FormGroup argument and returns a ValidationResult .

This is true since you are indeed returning a function that takes a FormGroup and returns a ValidationResult . The return type of the internal function is ValidationResult .

I understand : (group: FormGroup) means return type but then what does => ValidationResult mean here?

No. The return type is (group: FormGroup) => ValidationResult

Which means that the comparePasswords method returns a function that takes a FormGroup as argument and returns a ValidationResult . Ie it's a FormGroup validator.

You can see this code like the following :

{functionName}( {params}[] ) : {returnType} {
    {functionBody}
}

Where your functionName is comparePasswords
Your params is passwordKey: string, confirmPasswordKey: string
your returnType is (group: FormGroup) => ValidationResult

The type returned by your function is also a function.

When you execute comparePasswords , you get a function back.

If you execute this function, passing it a FormGroup , you will get a ValidationResult

In this block, it is returning a function which accepts an argument of type FormGroup and returns ValidationResult

Usually, in custom validation, we usually return null if the validation succeeds and return a key value pair denoted by type {[key:string]:string}

This key is used in the errors collection which you can use to validate whether your validation failed or succeeded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM