Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Argument of type 'string | null' is not assignable to parameter of type 'string | undefined'

The subject exists here also, but I’m still stuck.

I have an error in the isAuth() method:

Error: src/app/services/auth.service.ts:22:38 - error TS2345: Argument of type 'string 
| null' is not assignable to parameter of type 'string | undefined'.

Type 'null' is not assignable to type 'string | undefined'.

22     if(this.jwtHelper.isTokenExpired(token) || !localStorage.getItem('token')){  

I don’t understand what I have to change?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

isAuth():boolean{
    const token = localStorage.getItem('token');
    if(this.jwtHelper.isTokenExpired(token) || !localStorage.getItem('token')){
      return false;
    }
    return true;
}

code

>Solution :

the value of token is nullable because if there is no value for the key ‘token’ in your local storage, then localStorage returns null.
so what you can do is:
first check if there is a value for token or not.


isAuth():boolean{
    const token = localStorage.getItem('token');
    if((token && this.jwtHelper.isTokenExpired(token)) || !localStorage.getItem('token')){
      return false;
    }
    return true;
}

but the better approach is this:


isAuth():boolean{
    const token = localStorage.getItem('token');
    return token && !this.jwtHelper.isTokenExpired(token);
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading