1

I am using angular-jwt to to check whether token is expire or not and while using i am getting this error

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

helper = new JwtHelperService();

var token: string = localStorage.getItem('token');
this.helper.isTokenExpired(token); // this line contains the error

Error

enter image description here

enter image description here

6
  • What version of TypeScript you are using? Commented Dec 25, 2020 at 11:52
  • @slideshowp2 thank you for you response. I am using typescript version ~4.0.2. Commented Dec 25, 2020 at 11:54
  • Are you using npmjs.com/package/@auth0/angular-jwt? What's the version? Commented Dec 25, 2020 at 11:54
  • 1
    The error is exactly what it means: token can be null and it therefore cannot be passed into the argument that does not accept a potential null value. Check if the value is null or not before passing it. Or, if it is null change it’s value to undefined. Commented Dec 25, 2020 at 11:55
  • Yes i am using auth0/angular-jwt Commented Dec 25, 2020 at 11:56

5 Answers 5

3

First you should check your token

    var token: string = localStorage.getItem('token');
    if (token) {
       this.helper.isTokenExpired(token);
    }
Sign up to request clarification or add additional context in comments.

Comments

3

Maybe try adding an "if" condition before to check if "token" is not null:

var token: string = localStorage.getItem('token');
if (token)
   this.helper.isTokenExpired(token); // this line contains the error

1 Comment

localStorage.getItem('token') returns string|null, so it will cause typescript error if it is cast to string
2

Your token can't be null. Try

let token = localStorage.getItem('token');
token = token === null ? undefined : token;
this.helper.isTokenExpired(token);

Comments

0

Here is the solution.

let token: any = localStorage.getItem('token');

if (token == null)
  token = undefined;

return this.helper.isTokenExpired(token);

Comments

0

You are probably getting this error because your var token can have either string or null value that's why what you should do is provide it a null value as well in option.

like this,

helper = new JwtHelperService();

var token: string|null = localStorage.getItem('token');

this.helper.isTokenExpired(token);

this might help you Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.