DEV Community

Cover image for This condition will always return 'false' since the types X and Y have no overlap
Ibrahim Adeniyi
Ibrahim Adeniyi

Posted on

This condition will always return 'false' since the types X and Y have no overlap

There are a few reasons why typescript will throw this error.

  • Typescript enum limitations
  • Messing up logical operators.
  • Strictly comparing values of different types. In the last two cases, you can review your code logic and fix it.

Working with enums, you might inadvertently create a situation where you run into this error. Let's take a look at the typing below.

enum DashboardType {
  Shape = "Shape",
  SingleShape = "SingleShape",
  MultipleShapes = "MultipleShapes",
}
Enter fullscreen mode Exit fullscreen mode

Now, we have a type of dashboard that could be a single shape or multiple shapes dashboard, or either of the two.
In the case where the dashboard is a Shape dashboard, let's assume you have a component that uses this check to render or handle some logic.

if(dashboard === DashboardType.Shape)
Enter fullscreen mode Exit fullscreen mode

In the logic, if you have a check like

if(dashboard === DashboardType.Shape) {
    // some operations
    if(dashboard === DashboardType.SingleShape) {
       // some rendering/operation
    }
    if(dashboard === DashboardType.MultipleShapes) {
       // some rendering/operation
    }
}
Enter fullscreen mode Exit fullscreen mode

then typescript will throw an error like this This condition will always return 'false' since the types dashboard and DashboardType have no overlap.
You can use type coercion to fix the error like this:

(dashboard as DashboardType) === DashboardType.SingleShape.
Enter fullscreen mode Exit fullscreen mode

On the other hand, you can just improve your conditional logic and the enum type if you can afford too.
For example, the type DashboardType could become

{
  SingleShape = "SingleShape",
  MultipleShapes = "MultipleShapes",
}
Enter fullscreen mode Exit fullscreen mode

Then, to handle a shape component(regardless of whether it's single or multiple), you can have the logic like this:

if(dashboard === DashboardType.SingleShape || dashboard === DashboardType.MultipleShapes)
Enter fullscreen mode Exit fullscreen mode

Happy coding!.

Top comments (0)