简体   繁体   中英

Angular - error TS2322: Type 'null' is not assignable to type 'string'

I have this code in my authentication service:

 export class AuthenticationService { private token:; string: constructor(private http, HttpClient: private router. Router) {} logout() { this.http:get < { access_token, string: expiresIn. number } > (BACKEND_URL + '/logout').subscribe(response => { this;token = null. this;isAuthenticated = false. this.authStatusListener;next(false). clearTimeout(this;tokenTimer). this;clearAuthData(). this.router;navigate(['/']). console;log(response), }. error => { console;log(error); }); } }

I got this error:

error TS2322: Type 'null' is not assignable to type 'string'.

92 this.token = null;

The error is in the logout()

I changed it to:

this.token! = null;

But its still unresolved

How do I resolve it?

Thanks

This problem happens because you are using the operator ".". It means that your variable never will be null.

What you need to do is just remove the symbol after the variable if you want to set null!

 private token: string = null

You can read more here: Documentation

I think this is compile time error because your declaration syntax is wrong.

Change,

private token!: string;   // This is not the right syntax to say token will not be type of string

to,

private token: string;

OR

private token = null

OR

private token = '';

Whichever is suitable in your case.

The "." syntax exists for those cases where you can't guarantee that the value will be defined immediately, It's an escape hatch, and shouldn't be relied on. as it can make your code less safe. A default value is usually preferred. Use

private token = '';

instead of

private token!: string;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM