3

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?

3 Answers 3

7

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is also correct for the first problem but unfortunately I can mark only one answer.
6

Just try this

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

Hope this works for you

3 Comments

let logged: number = localStorage.getItem('logged'); returns Type 'string' is not assignable to type 'number'.
use this let logged: number = Number(localStorage.getItem('logged'));
glad that it helps you , please tick the answer for more convenience of users
0

This worked for me:

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

And when localStorage.getItem('logged')

"1514712216523"

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.