microsoft / microsoft/TypeScript

Type Inference In Switch Statement Not Work With &&

Aperta
#38,580 3 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Bug Domain: check: Control Flow
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

TypeScript Version: 4.0.0-dev.20200512

Search Terms: switch, inference, switch and inference

Code

interface I1 {
    type: 'I1';
    value: string;
}

interface I2 {
    type: 'I2';
    value: number;
}

type T = I1 | I2;

let t: T | undefined;

if (t && t.type == 'I1') {
    t.value; // Type string
}

switch (t?.type) {
    case 'I1':
        t.value; // Type string
        break;
}

switch (t && t.type) {
    case 'I1':
        t.value; // Uh oh, error
        t!.value; // Uh oh, string | number
        break;
}

Expected behavior:
The compile should understand that t && t.type is like as t?.type except that has also other falsy values.

Actual behavior:
The compiler does not infer from such expression.

Playground Link: https://www.typescriptlang.org/play/?ts=4.0.0-dev.20200512#code/JYOwLgpgTgZghgYwgAgJIEZkG8BQz-JgCeADhAFzIDkGVA3HgQG5wA2ArhcgM5hSgBzBgF8cOUJFiIUqAEzZG+YmUo1Z9RchYcuIdgFsARtBFjlKACrIAvGkwAfNLIY5WEMIUpXH7EABMIGFAIPxdgGGQACg8AMhjCADpzG1sadCoASgUCRO1OOmQAekLkC1IUXn4QARxRHG4Ad2AwBAALKLAAfiTyrNwchDhuFDSqck0csAS8iALi0vKePkEJgkMoCDgAa1N6ppb26OQ4xPM+zUHh6lpxnMnptnyikoBVdoB7VoAaZGgod6gqyUAEIHjo5q8Pt8llUBMhHHojNAgch1psdrUcEA

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 la riproduzione collegata in TypeScript Playground e confronta il comportamento del narrowing delle tre condizioni mostrate. Traccia l’analisi del flusso di controllo del compilatore per le espressioni switch che usano t \u0026\u0026 t.type; il lavoro è completo quando il ramo finale restringe t in modo coerente con il comportamento previsto.

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
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.