microsoft / microsoft/TypeScript

Union type resolving to one side of the union when spread operator is used

Aperta
#42,771 2 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

Bug Report

This issue may be related but they were different enough to warrant a write up here: https://github.com/microsoft/TypeScript/issues/42665

When assigning a union type to a variable, which is immediately instantiated as an object that could possibly be either type at run time, and the spread operator is used to "optionally" apply a property, the type of the variable falls to the type without the extra properties automatically.

🔎 Search Terms

Spread operator, object, union type

🕗 Version & Regression Information

This changed between versions 3.7.5 and 3.8.3.

⏯ Playground Link

Playground link with relevant code

💻 Code
interface Foo {
    bar: string;
}

type Bar = Foo & {
    baz: string;
}

const produceBoolean = () => Math.random() > 0.5;

const obj: Foo | Bar = {
    bar: 'baz',
    ...(produceBoolean() && {
        baz: 'bar'
    })
}

if ('baz' in obj) { // obj is "Foo" here
    console.log(obj); // obj is "never" here
}
🙁 Actual behavior

Instead of remaining a union type until some discrimination was made, it assumed the object was the side of the union without extra properties.

🙂 Expected behavior

It would remain possibly either or any type in the union until discriminated in the code.

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 dalla riproduzione collegata in TypeScript Playground e confrontane il comportamento tra le versioni segnalate 3.7.5 e 3.8.3. Traccia il percorso del controllo dei tipi per object spread in una union, quindi verifica che il valore risultante rimanga una union e che il controllo 'baz' in obj lo restringa correttamente.

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.