输入 'string' | null 不可分配给类型 'string'

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

我正在使用 angular-jwt 检查令牌是否过期,但在使用时出现此错误

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

您的令牌不能为空。尝试

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

也许可以尝试在检查“token”是否为空之前添加一个“if”条件:

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

这是解决方案。

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

if (token == null)
  token = undefined;

return this.helper.isTokenExpired(token);

首先你应该检查你的令牌

    var token: string = localStorage.getItem('token');
    if (token) {
       this.helper.isTokenExpired(token);
    }