Rule: no-promise-as-boolean
Warns for Promises that are used for boolean conditions.
For the most accurate findings, set "strict": true
in your tsconfig.json
.
It’s recommended to enable the following rules as well:
Rationale
There are no situations where one would like to check whether a variable’s value is truthy if its type only is Promise. This may only occur when the typings are incorrect or the variable has a union type (like Promise | undefined), of which the latter is allowed.
This rule prevents common bugs from forgetting to ‘await’ a Promise.
Notes:
Config
A list of ‘string’ names of any additional classes that should also be treated as Promises. For example, if you are using a class called ‘Future’ that implements the Thenable interface, you might tell the rule to consider type references with the name ‘Future’ as valid Promise-like types. Note that this rule doesn’t check for type assignability or compatibility; it just checks type reference names.
Config examples
"no-promise-as-boolean": true
"no-promise-as-boolean": [true, {"OPTION_PROMISE_CLASSES": ["Thenable"]}]
Schema
{ "type": "object", "properties": { "promise-classes": { "type": "array", "items": { "type": "string" } } } }
Code examples:
Disallows usages of a non-awaited Promise as boolean.
"rules": { "no-promise-as-boolean": true }
Passes
async function waiter(custumerDecisionPromise: Promise<any>) {
if (await custumerDecisionPromise) {
console.log("Customer ready to take an order.")
}
}
Fails
async function waiter(custumerDecisionPromise: Promise<any>) {
if (custumerDecisionPromise) {
console.log("Customer ready to take an order.")
}
}
Disallows usages of a non-awaited third-party promise as boolean.
"rules": { "no-promise-as-boolean": [true, { "promise-classes": ["CustomPromise"] }] }
Passes
function printOrdersPerLine(orderId: number, orderedFoodPromise: CustomPromise<string[]>) {
orderedFoodPromise.then(orderedFood => {
console.log(`${orderId} contains the following items:`);
for (let index = 0; orderedFood; index++) {
console.log("orderedFood[index]");
}
console.log("Done.");
})
}
Fails
function printOrdersPerLine(orderId: number, orderedFoodPromise: CustomPromise<string[]>) {
console.log(`${orderId} contains the following items:`);
for (let index = 0; orderedFoodPromise; index++) {
console.log("orderedFoodPromise[index]");
}
console.log("Done.");
}