Home > Net >  Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolea
Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolea

Time:10-02

I tried to insert an Auth System to the Angular App. (This one.

After finishing everything, I got for this code:

private userCurrentState = new BehaviorSubject<boolean>(this.tokenAuthService.isSignedin());

this error message

Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolean'.

TokenAuthService code

getJwtToken(){
    return localStorage.getItem('auth_token');
}

validateToken(){
 const token = this.getJwtToken();
 if(token){
   const payload = this.payload(token);
   if(payload){
     return Object.values(this.tokenIssuer).indexOf(payload.iss) > -1 ? true : false;
   }
 } else {
    return false;
 }
}

isSignedin() {
    return this.validateToken();
}

And I have no idea why. Anybody here to help? Thanks a lot :)

CodePudding user response:

The call this.tokenAuthService.isSignedin() could possibly return undefined, while the BehaviorSubject is expecting a boolean value.

You could get around this by using a boolean variable, and having the variable check the function call to set itself to true if it's true, or false if false or undefined.

CodePudding user response:

Allow BehaviourSubject to accept undefined data type change

private userCurrentState = new BehaviorSubject<boolean>(this.tokenAuthService.isSignedin());

to

private userCurrentState = new BehaviorSubject<boolean | undefined>(this.tokenAuthService.isSignedin());

Or

Since your isSignedin is depends on validateToken(), mark it return type as boolean

validateToken(): boolean{
     const token = this.getJwtToken();
     if(token){
       const payload = this.payload(token);
       if(payload){
         return Object.values(this.tokenIssuer).indexOf(payload.iss) > -1 ? true : false;
       }
       return false; // you can return false here
     } else {
        return false;
     }
  }
  • Related