Skip to content

Using Array and Boolean in condition does not trigger a warning #36227

@bodinsamuel

Description

@bodinsamuel

TypeScript Version: 3.8.0-dev.20200115

Search Terms: overlap boolean vs array condition

Code

function isAllowed() {
  const myCondition = false;
  if (myCondition === false) {
    return [];
  }

  return true;
}

if (isAllowed()) {
  // boolean and array will results in a "true" condition
  console.log('allowed');
} else {
  // never reached
  console.log('not allowed');
}

Expected behavior:

  • Seeing a message saying something like This condition can produce unexpected results since the types 'boolean' and 'array' have no overlap (not really good but you get the idea)

Actual behavior:
I won't say that it's a bug, but something that could be improved. I know that it's valid javascript but this a bug in the code that should/could be prevented by Typescript

  • Typescript does not complain that comparing boolean and array can results in bad condition

Already fixable by

  • It does complain if you write if (isAllowed() === true) but it's easy to not do it.

Playground Link: http://www.typescriptlang.org/play/?ts=3.8.0-dev.20200115&ssl=1&ssc=1&pln=15&pc=1#code/GYVwdgxgLglg9mABDAzgQQDYbgdwKYAmAFAJSIDeAUIohAilIgLYCeAwggTLAogLyIoAJxB4A3NWTBERVhzBceSPisEi8ZKjRpC8UEEKQBtALoSaAX0qTd+w4mABDDCnGUrlGNKKpM2fMQkmpJ0YChwGHgAdNgA5kQA5M7+hAkkEhaIeC54FCH0EdFxiWBwjMm4qenulEA

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions