-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Inconsistent inferred type predicate for filter #61182
Comments
This is working as intended. Only for specific cases the type guard will be inferred. See #57465, the "Interesting cases" section. The type guard must be true for all values of the narrowed type, but your second function does not fulfill that purpose. The related issue to tackle this limitation is #15048. Here's an example of the problem: Playground link const fn = (x: string | null): x is string => x !== null && x.startsWith('t')
declare const value: string | null
if (fn(value)) {
value;
// ^?
}
if (!fn(value)) {
value;
// ^?
} In the second if-check the type is narrowed to |
Thanks for your comment @MartinJohns, I guess the main problem is the "else" of the type inference, as it can still be a string. I think that Manual type inference it is then! const c = a.filter((x): x is string => x !== null && x.startsWith('t')) |
The team (which I'm not part of, just pointing out) does not like to hardcode special cases. This would lead to confusion, as people would expect the same behavior for their own types and implementations. Think of a So without #15048 this remains unsolved. |
π Search Terms
filter type predicate
π Version & Regression Information
This only makes sense since TS5.5, when inferred type predicates were introduced.
β― Playground Link
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAhjAvDA2gcigU2mgNDMAVwBtiBdAKAHoqY6YA9AfgotElgCMl4A6AMwCWxLACcAFAA8kAPhjSAhImRFSASmq16zVu2gxgPOAOFips+TCUqSxGADJ783tDiioEAOqCoAC3EYaGoaNPSMLBRAA
π» Code
π Actual behavior
On the above, the type of
b
is correctly inferred asstring[]
, but the type ofc
is incorrectly inferred to(string | null)[]
π Expected behavior
The inferred type of
c
shouldstring[]
, just like the inferred type ofb
.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: