microsoft / microsoft/TypeScript
[Control flow] Array filter with typeguard works differently following array initial value
Personne n'a encore pris cette issue.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.4k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 117
Description
🔎 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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par les exemples liés de TypeScript Playground et comparez les deux déclarations de raw : un tableau d’union vide et un tableau initialisé avec des valeurs. Examinez comment le type predicate de filter est vérifié pour chaque chemin de contrôle de flux. Le travail est terminé lorsque les deux exemples acceptent systématiquement l’affectation à string[] et que le comportement démontré est couvert par des tests.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100