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

avatar

Borislav Hadzhiev

Last updated: Mar 24, 2022

banner

Photo from Unsplash

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

The error "An expression of type 'void' cannot be tested for truthiness" occurs when we forget to return a value from a function and test the result for truthiness. To solve the error, make sure to return a value from the function or correct your conditional.

expression type void cannot be tested

Here are 2 examples of how the error occurs.

index.ts
// 👇️ function returns type void function sum(a: number, b: number) { const result = a + b; // 👉️ forgot to return } // ⛔️ Error: An expression of type 'void' cannot be tested for truthiness.ts(1345) const result = sum(10, 10) ? 20 : 0; // ⛔️ Error: An expression of type 'void' cannot be tested for truthiness.ts(1345) if (sum(10, 10)) { console.log('success'); }

We forgot to return a value from the sum function, so it implicitly has a return type of void.

The void type represents the return value of a function, which doesn't return a value.

When you don't return a value from a function, you implicitly return undefined, and the function's return type is inferred to be void.

We can't test an expression of type void for truthiness. It will always return false, because undefined is a falsy value.

To solve the error, make sure the function you are using in the conditional returns a value.

index.ts
// 👇️ function now returns a value function sum(a: number, b: number): number { const result = a + b; return result; // 👈️ explicit return } const result = sum(10, 10) ? 20 : 0; if (sum(10, 10)) { console.log('success'); }

Now the sum function has a return type of number.

A helpful way to debug this is to explicitly set the function's return type like in the example above. If you forget to return a value of the specified type, you would get a helpful error message.

If you're using an implicit return with an arrow function, make sure the function returns the expected value.

index.ts
// 👇️ implicit return with objects const getObj = () => ({ name: 'Tom', country: 'Chile', }); // 👇️ implicit return with primitives const getNum = (a: number, b: number) => a + b;

If you didn't intend to test the return value of the function for truthiness, you need to update your conditional and test for something else.

Conclusion #

The error "An expression of type 'void' cannot be tested for truthiness" occurs when we try to test the return value of a function that doesn't return anything for truthiness. To solve the error, return a value from the function or update your conditional to test for something else.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.