microsoft / microsoft/TypeScript

Type guard does not narrow the same as if-statement

Offen
#33,119 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Awaiting More Feedback Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

TypeScript Version: 3.5.1

Search Terms:

  • Type guard function
  • If-statement guard
  • Narrow
  • Discriminated union

Code

enum E1 {
    element0 = "element0",
    element1 = "element1",
    element2 = "element2",
}
enum E2 {
    element3 = "element3",
    element4 = "element4",
    element5 = "element5",
}

declare const obj : (
    | {
        type : E1,
        data : {
            object : {
                x : "e1"
            }
        }
    }
    | {
        type : E2,
        data : {
            object : {
                x : "e2"
            }
        }
    }
);

if (obj.type == E1.element0) {
    //OK
    const type : "element0" = obj.type;
    //OK
    const x : "e1" = obj.data.object.x;
}

if (
    obj.type == E1.element0 ||
    obj.type == E1.element1 ||
    obj.type == E1.element2
) {
    //OK
    const type : "element0"|"element1"|"element2" = obj.type;
    //OK
    const x : "e1" = obj.data.object.x;
}

declare function isE1 (mixed : unknown) : mixed is E1;

if (isE1(obj.type)) {
    //OK
    const type : "element0"|"element1"|"element2" = obj.type;
    //Expected : OK
    //Actual : Error; Type '"e1" | "e2"' is not assignable to type '"e1"'.
    const x : "e1" = obj.data.object.x;
}

Expected behavior:

2nd and 3rd examples should both work.

Actual behavior:

2nd example works.
3rd example does not work.

Playground Link:

Playground

Related Issues:

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 mit der bereitgestellten Playground-Reproduktion und vergleiche die direkten enum-Prüfungen mit dem benutzerdefinierten isE1-Typwächter. Untersuche die Control-Flow-Narrowing von TypeScript für discriminated unions und überprüfe das erwartete Ergebnis: Das dritte Beispiel sollte obj.data.object.x auf "e1" eingrenzen. Füge einen Regressionstest hinzu oder aktualisiere ihn, falls der relevante Speicherort für Compiler-Tests identifiziert wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

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