Is there a ESLint rule to prevent `Promise<boolean>` to `boolean` cast

Viewed 424

I want a rule to prevent a Promise<boolean> from being cast to a boolean:

// ERROR: This is always true because it is a promise
if( !authorize() ){
  throw new Error('Go away!');
}

Correct:

// Good, only true if the promise result is true
if( !await authorize() ){
  throw new Error('Go away!');
}

Given something like this:

async authorize(){
  // I don't really support bribery
  return await doesUserHaveCredentials() || didUserPayMeABunchOfMoney();
}

Rules I have tried:

  • require-await: Seems a good name for this, but this rule just checks if an async function contains an await somewhere
  • @typescript-eslint/no-floating-promises: Helpful, but doesn't prevent the boolean cast
  • @typescript-eslint/strict-boolean-expressions: Doesn't help in this case

Is anyone aware of a rule that would error on if(!promise())?

1 Answers

I think you want the checkConditionals option (which is enabled by default) in @typescript-eslint/no-misused-promises:

Examples of incorrect code for this rule with checksConditionals: true:

const promise = Promise.resolve('value');

if (promise) {
  // Do something
}
Related