microsoft / microsoft/TypeScript
discriminated union type narrow when destructuring object within desturct array
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
🔎 Search Terms
destructuring object within destructured array, discriminated union
🕗 Version & Regression Information
the error part appeared in every version I tried
⏯ Playground Link
💻 Code
type FirstItem = {
type: 'first'
value: string
}
type SecondItem = {
type: 'second'
value: number
}
type ThirdItem = {
type: 'third'
value: boolean
}
const a: (FirstItem | SecondItem | ThirdItem)[] = []
// test 1
a.forEach(({ type, value }) => {
if (type === 'first') {
// ok: string
console.log(value)
}
})
// test 2
for (const { type, value } of a) {
if (type === 'first') {
// ok: string
console.log(value)
}
}
const b: [ FirstItem | SecondItem | ThirdItem ][] = []
// test 3
for (const [ v ] of b) {
if (v.type === 'first') {
// ok
console.log(v.value)
}
}
// test 4
b.forEach(([{ type, value }]) => {
if (type === 'first') {
// not ok: string | number | boolean
console.log(value)
}
})
// test 5
for (const [ { type, value } ] of b) {
if (type === 'first') {
// not ok: string | number | boolean
console.log(value)
}
}
🙁 Actual behavior
the code above, test4 and test5 can not narrow to the string type like test1, test2 or test3
🙂 Expected behavior
I expected the value in the loop to infer successfully
Additional information about the issue
No response
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
Beginne mit dem Playground Link und reproduziere die Tests 4 und 5 aus dem Issue, indem du sie mit den Tests 1–3 vergleichst. Verfolge das Verhalten der Typprüfung für destrukturierte Objekte innerhalb destrukturierter Arrays; abgeschlossen ist es, wenn die Variable value auf string eingegrenzt wird, wenn type 'first' ist.
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