microsoft / microsoft/TypeScript

Aliased Conditions with explicit type definition results in the "old" behavior

Offen
#45,469 4 Kommentare 1 Reaktion 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

Bug Report

🔎 Search Terms

Aliased Conditions

🕗 Version & Regression Information

V4.4.0-beta / nightly

  • I was unable to test this on prior versions because it is a new feature
⏯ Playground Link

Playground link with relevant code

💻 Code
type Shape =
    | { kind: "circle", radius: number }
    | { kind: "square", sideLength: number };

function area(shape: Shape): number {
    const isCircle: boolean = shape.kind === "circle";
    if (isCircle) {
        // We know we have a circle here!
        return Math.PI * shape.radius ** 2;
    }
    else {
        // We know we're left with a square here!
        return shape.sideLength ** 2;
    }
}
🙁 Actual behavior

Adding the explicit type to "isCircle" results in that the sample breaks

Property 'radius' does not exist on type 'Shape'.
  Property 'radius' does not exist on type '{ kind: "square"; sideLength: number; }'.
Property 'sideLength' does not exist on type 'Shape'.
  Property 'sideLength' does not exist on type '{ kind: "circle"; radius: number; }'.
🙂 Expected behavior

Making the implicit type explicit, does not result in the behavior to change.

Using the sample provided by the TS 4.4 RC announcement, getting the implicit type of "isCircle" (by hovering over it) yields boolean
image
. By then explicitly defining the type (boolean), the Aliased Conditions seems to break/revert back to pre 4.4 behavior.

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 dem verlinkten TypeScript Playground und reproduziere den Unterschied zwischen den inferierten und explizit annotierten isCircle-Bedingungen. Untersuche das Control-Flow-Narrowing des Compilers für aliasierte Bedingungen; abgeschlossen ist die Untersuchung, wenn die explizite boolean-Annotation das Narrowing in beiden Zweigen ohne die gemeldeten diagnostics beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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