microsoft / microsoft/TypeScript
[Control flow] Array filter with typeguard works differently following array initial value
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
🔎 Search Terms
filter + typeguard + control flow + strictNullChecks
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about filter + typeguards + control flow + strictNullChecks
⏯ Playground Link
💻 Code
const raw: string[] | (string | null)[] = [];
const filtered: string[] = raw.filter((step: string | null): step is string => typeof step === 'string') // KO
// Type '(string | null)[]' is not assignable to type 'string[]'.
const raw: string[] |(string | null)[] = ["plop", null];
const filtered: string[] = raw.filter((step: string | null): step is string => typeof step === 'string') // OK no error
🙁 Actual behavior
There is a strange difference in control flow when you filter nullish values in an array regarding the declaration of that array. This is definitely a edge case. The type string[] | (string | null)[] comes from an union type in my case.
🙂 Expected behavior
No difference and typeguard should work (regardless the fact it is valid).
Additional information about the issue
I first thought it was a regression due to #57465 but I tested it on several version. The issue has always been here. I looked into a lot of issues about typeguards and filters but unfortunately, could not find one similar to my issue 😢
Thanks anyway for the great job
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 den verlinkten TypeScript Playground-Beispielen und vergleiche die beiden Deklarationen von raw: ein leeres Union-Array gegenüber einem mit Werten initialisierten Array. Untersuche, wie filter's type predicate für jeden Control-Flow-Pfad geprüft wird. Als abgeschlossen gilt die Aufgabe, wenn beide Beispiele die Zuweisung zu string[] konsistent akzeptieren und das demonstrierte Verhalten durch Tests abgedeckt 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