An Expression of Type 'Void' Cannot Be Tested for Truthiness

I don't want to push null, so I'm putting a condition to check, but there's a syntax error that says:

"An expression of type 'void' cannot be tested for truthiness"

How do I do this correctly?

localStorage.setItem('todoitems', JSON.stringify(this.todoitems)) 
  ? localStorage.setItem('todoitems', JSON.stringify(this.todoitems)) 
  : [];
3

1 Answer

Since setItem doesn't return anything, it is complaining about using a void type in a ternary operator where a boolean is expected

You can add an if condition on this.todoitems before setItem

if (this.todoitems !== null)
    localStorage.setItem('todoitems', JSON.stringify(this.todoitems))
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest