TypeScript: Unexpected error: TS2365: Operator '!==' cannot be applied to types 'false' and 'true'

TypeScript Version: 2.1.4

This code in my VS Code extension has stopped compiling (without changes) recently.

if (context.globalState.get(stateKey, false) !== true)
    // blah

It returns the error:

src/user_config_prompts.ts(17,6):
    error TS2365: Operator '!==' cannot be applied to types 'false' and 'true'.

The full source is here and the build output here.

It seems like TypeScript has decided that the call to get can only return false, and therefore this comparison is bad; however I don’t believe that’s true - this method access stored state, so I can put some value in it and then reload my extension and it would receive the stored value.

This may be the same as #12772, but the response is confusing to me:

the function expression is not considered part of the flow, since it is not guaranteed to execute

This logic seems flawed - you can’t assume something can never have a certain value because it might not be called; surely you have to assume it might have that value because you do not know if it will be called?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 3
  • Comments: 20 (9 by maintainers)

Most upvoted comments

Oh yeah, I see that, and cool that the compiler now catches that! 😃

In sanitising the internal code, I removed the mutation:

function  getLengthAsStr(strs: string[]): string {
  if(strs.length !== 222){
     return "not 222"
  }
  //strs.length == 222
  strs.push("morestring")
 //strs.length == 223
  if(strs.length === 223){
    return "223"
  }
  return "blah"
}

which also fails to compile.

function  getLengthAsStr(strs: string[]): string {
  if(strs.length !== 111){
     return "111"
  }
  // `strs.length` here can not be any thing other than `111`
  // this check is guaranteed to be true
  if(strs.length !== 222){
    return "222"
  }
  return "blah"
}

@aluanhaddad I know, but the error message provided by the compiler is misleading. I also want to stress that sometimes this is happening even when there’s no unreachable code, but I couldn’t reproduce/isolate the scenario yet.

Your second else if is actually a bug that the compiler is catching for you. It’s dead code. The branch will never be taken because the previous else’s if checks for the same condition