-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Set.has() and Array.includes() should narrow the type of their argument to the type of this when they return true #51678
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
Comments
Yikes, this also requires #15048 even though that behavior isn't documented in https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates. |
If you mean the requirement that type predicates be exhaustive, that is documented, albeit admittedly somewhat offhandedly:
which implies the type predicate must be exhaustive. |
Essentially a duplicate of #36275 |
Is this that complicated? This seems to fulfill the requirement already: /** Shouldn't this be the type signature of Array.prototype.includes? */
function arrayIncludes<T>(arr: T[], v: unknown): v is T {
return arr.includes(v as T);
} I assume I am missing something but couldn't the type signature simply be changed to this? |
There's a code snippet in this comment that shows why you can't do this, but explicitly: Type predicates also narrow in the Without direct support for #14520 and #15048, writing a version of this that doesn't have weird side effects is ugly, and not anything the TS team wants to merge into the standard library. This is mostly all covered in #36275. |
I think this Playground illustrates the issue with that signature nicely. Or even better, this one: Playground |
To be clear, #15048 is required for the reasons explained by @jcalz. #14520 is optional (the alternative is to type the search term as |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
lib Update Request
Configuration Check
My compilation target is
ES2022
and my lib isthe default
.Missing / Incorrect Definition
Set.has()
andArray.includes()
should narrow the type of their argument to the type ofthis
when they return true (which implies they should accept wider types as arguments).This is probably impossible until #14520 is solved, but I wanted to add a more concrete use case than just making it convenient to pass wide arguments.
Sample Code
Playground Link
Documentation Link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has
The text was updated successfully, but these errors were encountered: