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?
Boolean values are supported by both JavaScript and TypeScript and stored as true/false values. TypeScript Boolean: let isPresent:boolean = true; Note that, the boolean Boolean is different from the lower case boolean type.
Use the typeof operator to check if a value is of boolean type, e.g. if (typeof variable === 'boolean') . The typeof operator returns a string that indicates the type of a value. If the value is a boolean, the string "boolean" is returned.
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned. Copied!
The typescript boolean is the default and pre-defined primitive data type that can be accepted only true or false, 0 or 1 boolean type of values.
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:
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.
I came across a similar issue and found the strict-boolean-expressions
rule. Not the perfect answer for the example given by the OP, but might be helpful for others.
Activating this rule causes expressions like
if (nonBooleanCondition) {
to display the following warning:
This type is not allowed in the 'if' condition because it is a [TYPE]. Only booleans are allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With