Reputation: 488
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?
Upvotes: 2
Views: 356
Reputation: 569
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:
if (bool) { ... }
(highly recommended)if((bool as boolean) === true ) { ... }
(it works but please don't do this)Upvotes: 1