-
-
Notifications
You must be signed in to change notification settings - Fork 135
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
Question: How can I make a pattern for "if array contains a certain element"? #193
Comments
There are variadic tuple patterns as of V5, but you can only have one variadic pattern in the array, so that won't work for this particular case. TS doesn't allow this, either: A usable type would likely have to be of the form Even if the type is not very meaningful (How could it be, actually? What more would Still, that's just the typing. What's needed here is the run-time support. |
The simplest/easiest is probably to use match(array)
.when((arr) => arr.includes("error"), () => console.log("array contains 1 or more errors"))
.otherwise(() => console.log("no errors")); I assume this a very simplified example, because otherwise you could just use |
@darrylnoakes Great, I think |
I agree that having something built in for more advanced variants would be nifty. For example, matching an array that contains an object that matches a certain pattern, and selecting that object. Basically, the normal use of After not too much thought, I propose adding a match(array).with(
P.array.some("error"), // Matches
() => "array contains 1 or more errors",
);
match(array).with(
P.array.some(P.select({ optionalKey: P.not(P.nullish()) })), // The selection is an _array_ of values that match. Or maybe an array of pairs of indices and values...
(values) => values,
); |
Adding this as a builtin to ts-pattern is a good idea. I'd probably name it |
I have another solution in the interim:
|
I am trying to detect if an array has a certain element. It's position in the array is unknown
Example of what I was thinking of (but doesn't work):
Is there a matcher for a single element in an array and not just the head or last element specifically?
The text was updated successfully, but these errors were encountered: