Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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)) 
  : [];
like image 310
Malik Shafi Avatar asked Aug 02 '19 10:08

Malik Shafi


1 Answers

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))
like image 143
adiga Avatar answered Oct 18 '22 15:10

adiga