microsoft / microsoft/TypeScript

Using Array and Boolean in condition does not trigger a warning

Offen
#36,227 11 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

In Discussion Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, das Verhalten im verlinkten TypeScript Playground anhand des bereitgestellten Beispiels und des aktuellen Compilerverhaltens zu reproduzieren. Verfolge den Typprüfpfad für Bedingungen, die boolesche Werte und Array-Werte enthalten; abgeschlossen ist die Aufgabe, wenn für die inkompatible Bedingung eine geeignete Diagnose ausgegeben wird, ohne gültige JavaScript-Muster abzulehnen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.