microsoft / microsoft/TypeScript
Union type resolving to one side of the union when spread operator is used
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie mit der verknüpften TypeScript Playground-Reproduktion und vergleichen Sie ihr Verhalten zwischen den gemeldeten Versionen 3.7.5 und 3.8.3. Verfolgen Sie den Type-Checking-Pfad für object spread in eine Union und überprüfen Sie anschließend, dass der resultierende Wert eine Union bleibt und die Prüfung 'baz' in obj ihn korrekt eingrenzt.
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
- 35/100