-
-
Notifications
You must be signed in to change notification settings - Fork 113
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
Improve type guard for .all
#81
Comments
That’s possible I guess if there’s a way to know if the predicate is a type guard predicate |
We don’t need to know it’s a type guard. We can just pass on what TS infers, maybe by using the |
Someone mentions the "built in altho, following this issue: interface Array<T> {
filter<U extends T>(pred: (a: T) => a is U): U[];
} type Predicate<T> = (value: unknown) => value is T;
is.all = <T>(predicate: Predicate<T>, ...values: unknown[]): values is T[] =>
predicateOnArray(Array.prototype.every, predicate, values); does this look right? |
Looks good. Can you do a PR? :) |
@IssueHunt has funded $30.00 to this issue.
|
I ran into this recently and tried the suggested fix, it looks like this isn't possible generically. export type Predicate<T = unknown> = (value: unknown) => value is T;
is.all = <T>(predicate: Predicate<T>, ...values: unknown[]): values is T[] =>
predicateOnArray(Array.prototype.every, predicate, values); Gives the error Apparently it also isn't possible to do this manually for a few arguments. This is a compile error (and all the other variants I tried). function test(a: unknown, b: unknown): (a is true) & (b is true) {
return true;
} |
@Gerrit0 Thanks for looking into it! to what line does this error refer to? is it thrown from |
The error is caused by It is possible to achieve the goal in the OP with a different signature. This works as expected (no changes necessary for is.allArray = <T>(predicate: Predicate<T>, values: unknown[]): values is T[] =>
predicateOnArray(Array.prototype.every, predicate, values) |
Any update on this issue ? |
@nicosayer I think you can use |
I am not sure how this helps, can you elaborate ? To make sure everything is clear, this is how I would summarize the issue: What is currently happening: let a: string | number
let b: string | number
if (is.all(is.string, a, b)) {
// `a` and `b` are of type string | number
} What is actually expected: let a: string | number
let b: string | number
if (is.all(is.string, a, b)) {
// `a` and `b` are of type string
} |
@nicosayer yeah my bad, I've been out of context for a while and thought it would work, but it doesn't type-guard the specific array items |
It would be nice if this worked:
The text was updated successfully, but these errors were encountered: