Home > Mobile >  Condition Overlaps in Typescript
Condition Overlaps in Typescript

Time:05-27

Lets say I have some simple logic like this:

let bool = false

const seven = 7
const arr = [1,2,3,4,5,6,7]
    
arr.forEach(element => {
    if (element === seven) {
        bool = true
    }
});

Now I wan't to call a function if "bool" has been set to true:

if (bool === true){
    doSomething()
}

Typescript gives an error in this case:

This condition will always return 'false' since the types 'false' and 'true' have no overlap.

Typescript complains even though logically I know that bool will be true by the time the condition block is triggered. How do I resolve this?

CodePudding user response:

I did not know that the Typescript compiler would complain on something like this, but again it's a strange way to have such a condition statement since:

if (bool === true)

is the same as:

if (bool)

But yeah you can either:

  1. Write the condition in a normal way: if (bool) { ... } (highly recommended)
  2. Force the type to be boolean: if((bool as boolean) === true ) { ... } (it works but please don't do this)
  • Related