简体   繁体   中英

Argument of type 'number' is not assignable to parameter of type 'string'

I was trying to set UNIX time in local storage by:

let dt: number = Date.now();
localStorage.setItem('logged', dt+864000000);

Returning with error: Argument of type 'number' is not assignable to parameter of type 'string'

It's giving the same error when i use getItem to read the logged data.

Any solution?

All items in local storage are strings . You're trying to pass a number in as the second argument to setItem when setItem 's second paramter is type string , so naturally TypeScript warns you (because you've asked for type safety) that you can't do that.

If you want to store in local storage, explicitly turn it into a string:

let dt: number = Date.now();
localStorage.setItem('logged', String(dt+864000000));

Just try this

let dt: number = Date.now();
localStorage.setItem('logged', ""+dt+864000000);

Hope this works for you

This worked for me:

let dt = Date.now();
localStorage.setItem('logged', dt+864000000);

And when localStorage.getItem('logged')

"1514712216523"

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