简体   繁体   中英

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

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()) ?

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM