microsoft / microsoft/TypeScript

Using Array and Boolean in condition does not trigger a warning

Open
#36,227 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the behavior in the linked TypeScript Playground using the provided example and current compiler behavior. Trace the type-checking path for conditions involving boolean and array values; done means an appropriate diagnostic is produced for the incompatible condition without rejecting valid JavaScript patterns.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.