Home > OS >  Typescript validate multiple condition passed as function parameter
Typescript validate multiple condition passed as function parameter

Time:12-01

I'm new to TS/JS, I want to validate multiple condition passed as argument to the function

For example, here I'm checking for user role name, tmrw I might need to check some other condition

  validateUserDetails(): Promise<Boolean> {
    return new Promise<Boolean>((resolve, reject) => {
      this.currentLoggedInUserRole = this.sharedService.getCurrentUser()['roleName'];
      if (this.currentLoggedInUserRole) {
        let url = `<some GET url>`;
        this.http
          .get<any>(url)
          .pipe(
            take(1),
            catchError((error) => {
              reject(false);
              return throwError(error);
            })
          )
          .subscribe((response: any) => {
            if (
              response.length > 0 && response.some((user) => user['roleName'] === this.currentLoggedInUserRole)) {
              resolve(true);
            } else {
              resolve(false)
            }
          });
      }
    });
  }
this.userValidationService.validateUserDetails().then(isUserValid => {
  //some logic
}).catch((error) => {console.log(new Error(error))})

I want to pass the conditions to be check as argument to the function something below, tmrw I might have multiple values to pass I don't to pass as comma separated values, I want to pass may be like arrays or maps.this.userValidationService.validateUserDetails(['userRole', userID]).

this.userValidationService.validateUserDetails('userRole').then(isUserValid => {
  //some logic
}).catch((error) => {console.log(new Error(error))})

So my question is how can i pass arguments with multiple condition, If yes how can i handle inside my promise to check all/ partial conditions. Thank you

CodePudding user response:

You may looking for TypeScript - Rest Parameters

validateUserDetails(...fields: string[]): Promise<Boolean> {
  ...
}

Then you can pass function's parameters as sperate (comma) or array, the result sill be the same.

this.userValidationService.validateUserDetails(['userRole', 'userID', ...])

or

this.userValidationService.validateUserDetails('userRole', 'userID', ...)
  • Related