Is there a way to force "if" to only accept boolean in TypeScript?

The following code is legal in TypeScript:

let asyncCondition = async(): Promise<boolean> => // .. calculate & return a boolean
if(asyncCondition()){ // forgot to await. condition is always true
  // .. do stuff
}

Since asyncCondition() returns a normal not-null Promise , the code in if block will always get executed. This is JavaScript behavior and it's understandable that TypeScript doesn't complain.

But in the above scenario, what I really meant is:

let asyncCondition = async(): Promise<boolean> => // .. calculate & return a boolean
if(await asyncCondition()){ // condition is asyncCondition()
  // .. do stuff
}

Is there a way to let TypeScript to type check this kind of errors for me?


The compiler does not do it and I won't expect it to do it any time soon. It has been asked and rejected a number of times. The cases I could find:

  • Feb 2016: https://github.com/Microsoft/TypeScript/issues/7306
  • Apr 2016: https://github.com/Microsoft/TypeScript/issues/8178
  • Jul 2016: https://github.com/Microsoft/TypeScript/issues/9702
  • In each cases, the reasoning for closing these issues without changing the compiler was that it would be too radical a change, and that really a linter should do this job.

    The good news is that a new rule has recently been merged into tslint 's codebase to provide warnings about this problem. As far as I can tell, though, the rule is not yet in a released version of tslint . Once it is released, if you set strict-boolean-expressions to true in your tslint rules, then tslint will warn you when you use a conditional with an expression that is not strictly boolean.

    链接地址: http://www.djcxy.com/p/37616.html

    上一篇: Windows上的Python多处理和联网

    下一篇: 有没有办法强制“if”只接受TypeScript中的布尔值?