Skip to content

asFilterMatch

asFilterMatch<T, C>(item: T, condition: C): T & HasFilterValues<T, C>

Defined in: match-filters.ts:48

Asserts that an item matches the filter conditions, returning the item if so. Throws an error if the item does not match.

Type Parameter
T extends Record<string, any>
C extends NestableFilters<T>
ParameterTypeDescription
itemTThe object to test.
conditionCThe filter conditions to match.

T & HasFilterValues<T, C>

The item, typed as matching the filter values.

Error if the item does not match the filter.

This function is useful for enforcing that an object matches filter criteria, throwing an error if not. It is commonly used for validation, assertions, and type narrowing.

export function asFilterMatch<
T extends Record<string, any>,
C extends NestableFilters<T>,
>(item: T, condition: C): T & HasFilterValues<T, C> {
if (matchFilters(item, condition)) {
return item;
}
throw new Error("not a match");
}
const item = { status: "active", role: "admin" };
const filter = { status: "active" };
asFilterMatch(item, filter); // returns item
asFilterMatch(item, { status: "inactive" }); // throws Error