mikefolu
mikefolu

Reputation: 1333

Angular - error TS7030: Not all code paths return a value in Angular RoleCheck

I have this function in service to check roles in Angular11 Project:

// tslint:disable-next-line:typedef
  checkRole(role: string){
   // const roles = JSON.parse(localStorage.getItem('roles'));
    const roles = JSON.parse(localStorage.getItem('roles') || '{}');
    if (!roles) {
      return false;
    }
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < roles.length; i++){
      if (roles[i] === role) {
        return true;
      }
      return false;
    }
  }

I got this error:

error TS7030: Not all code paths return a value.

62 checkRole(role: string){

How do I get it sorted out?

Thank you

Upvotes: 2

Views: 3255

Answers (3)

OctavianM
OctavianM

Reputation: 4597

You should move your return false; outside of the for loop. I took the opportunity to rewrite your function a bit. Try this instead:

  checkRole(role: string): boolean {
    const roles = JSON.parse(localStorage.getItem('roles') || '[]') as string[];
    if (!roles) {
        return false;
    }

    return roles.some(r => r === role);
  }

Upvotes: 0

Wajid
Wajid

Reputation: 593

It is because your not return for whole function thats why it give you error , check below if it work otherwise return value at end of function so it will return all part of code

// tslint:disable-next-line:typedef
      checkRole(role: string){
       // const roles = JSON.parse(localStorage.getItem('roles'));
        const roles = JSON.parse(localStorage.getItem('roles') || '{}');
        if (!roles) {
          return false;
        }
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < roles.length; i++){
          if (roles[i] === role) {
            return true;
          }
          
        }
    return false;
      }

Upvotes: 0

Beka Kalandadze
Beka Kalandadze

Reputation: 600

Your first if block:

if (!roles) {
  return false;
}

is missing an else condition which must return something. You can disable this rule by providing tsconfig.json

  "noImplicitReturns": false

or add a return condition to the end of the code.

Upvotes: 3

Related Questions