Is there a way to force the if to accept only a 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 non-null Promise , the code in the if block will always be executed. This is JavaScript behavior, and it is clear that TypeScript is not complaining.

But in the above scenario, I had in mind:

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

Is there a way to let TypeScript print such errors for me?

+7
typescript
source share
1 answer

The compiler does not do this, and I will not expect it to do this any time soon. He was asked and rejected several times. Cases I could find:

In each case, the argument for closing these problems without changing the compiler was that it would be too radical a change, and that in fact linter should do the job.

The good news is that a new rule has been recently tslint to tslint codebase to provide warnings about this issue. However, as far as I can tell, the rule has not yet been released in the tslint version. When it is released, if you set strict-boolean-expressions to true in your tslint rules, then tslint warn you when you use a conditional expression with an expression that is not strictly logical.

+3
source share

All Articles