smaccoun
smaccoun3w ago

Types for resuing filters

Anyone know how to type a filter we may want to reuse? Goal:
const someReusedFilter = (q: QueryInitializer<>) => q.filter(q.eq("someField", true))
const someReusedFilter = (q: QueryInitializer<>) => q.filter(q.eq("someField", true))
I can see that e.g. a query is a QueryInitializer or OrderedQuery but can't quite figure out how to type the parameters etc
5 Replies
Convex Bot
Convex Bot3w ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
smaccoun
smaccounOP3w ago
Although given the recommendation in best practices docs to not use filter maybe I should not be doing this
lee
lee3w ago
const someReusedFilter = <Q extends Query<TableInfo>>(q: Q): Query<TableInfo> => q.filter(q.eq("someField", true))
const someReusedFilter = <Q extends Query<TableInfo>>(q: Q): Query<TableInfo> => q.filter(q.eq("someField", true))
but also yeah filters are not recommended
lee
lee3w ago
Using TypeScript to Write Complex Query Filters
There’s a new Convex helper to perform generic TypeScript filters, with the same performance as built-in Convex filters, and unlimited potential.
smaccoun
smaccounOP3w ago
Thank you! For reference for anyone else who sees this, here's an exmaple i have using the convex helpers filter
import { filter } from "convex-helpers/server/filter";
import type { NamedTableInfo, Query } from "convex/server";
import type { DataModel } from "../_generated/dataModel";

export const hasLastNameFilter = <
Q extends Query<NamedTableInfo<DataModel, "users">>,
>(
query: Q
) =>
filter(query, (user) => user.lastName !== undefined && user.lastName !== "");
import { filter } from "convex-helpers/server/filter";
import type { NamedTableInfo, Query } from "convex/server";
import type { DataModel } from "../_generated/dataModel";

export const hasLastNameFilter = <
Q extends Query<NamedTableInfo<DataModel, "users">>,
>(
query: Q
) =>
filter(query, (user) => user.lastName !== undefined && user.lastName !== "");

Did you find this page helpful?