microsoft / microsoft/TypeScript

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

Aperta
#45,469 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

In Discussion Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.4k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

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.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il TypeScript Playground collegato e riproduci la differenza tra le condizioni isCircle inferite e annotate esplicitamente. Analizza il narrowing del flusso di controllo del compilatore per le condizioni alias; il lavoro è completato quando l’annotazione esplicita di tipo boolean mantiene il narrowing in entrambi i rami senza i diagnostics segnalati.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
38/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.