Last updated: Feb 29, 2024
Reading timeยท2 min
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.
Here are 2 examples of how the error occurs.
// ๐๏ธ 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 type of a function that
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
.
false
, because undefined
is a falsy value.To solve the error, make sure the function you are using in the conditional returns a value.
// ๐๏ธ 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 as in the example above. If you forget to return a value of the specified type, you will get a helpful error message.
If you're using an implicit return with an arrow function, make sure the function returns the expected value.
// ๐๏ธ implicit return with objects const getObj = () => ({ name: 'Bobby Hadz', 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.
If you explicitly set the function's return type but forget to return a value from the function, you'd get the A function whose declared type is neither void nor any must return a value error.
You can learn more about the related topics by checking out the following tutorials: