An expression of type ‘void’ cannot be tested for truthiness angular 7

An expression of type ‘void’ cannot be tested for truthiness angular 7

The Correct Answer and Explanation is:

Correct Answer:

The error “An expression of type ‘void’ cannot be tested for truthiness” in Angular (or TypeScript) typically occurs when you’re trying to use a function that returns void (i.e., returns nothing) in a condition like an if statement or a ternary operator.

Example of Incorrect Code:

if (this.doSomething()) {
  // Do something else
}

Here, if doSomething() is defined as:

doSomething(): void {
  console.log('Doing something...');
}

This causes the error because you’re testing a void return value in a truthy check.


Corrected Code:

To fix it, you need to return a boolean from the function, or separate the function call from the condition.

Option 1: Make doSomething() return a boolean:

doSomething(): boolean {
  console.log('Doing something...');
  return true; // or some condition
}

if (this.doSomething()) {
  // Now this works
}

Option 2: Call the function separately:

this.doSomething(); // Just execute the function

if (someOtherCondition) {
  // Use a proper condition here
}

300-Word Explanation:

In TypeScript (which Angular uses), every function has a return type. A function that does not explicitly return a value is typed as void. When you try to use such a void-returning function in a conditional statement (like an if), the compiler throws an error: “An expression of type ‘void’ cannot be tested for truthiness”.

This happens because void means “undefined”, and TypeScript enforces type safety. Unlike JavaScript, where you can loosely check undefined in conditions, TypeScript requires that the condition in an if statement be of a boolean-compatible type (like boolean, number, string, etc.), not void.

If you want to use a function inside an if statement, it must return a value—typically a boolean. Alternatively, if your function is only performing an action (like logging or modifying state) and not returning anything meaningful, you should not use it in a truthiness check. Instead, call the function separately and use another valid condition in your if.

This error encourages clean separation between action (procedures) and evaluation (conditions), which improves code readability and reduces logical bugs in Angular applications.

Scroll to Top