export type FILTER_META =
| {
type: 'string';
key: string;
filters: { id: string; label?: string }[];
}
| {
type: 'time';
key: string;
filters: { min: string; max: string }[];
}
| {
type: 'range';
key: string;
filters: { min: number; max: number }[];
};
type Unpacked<T> = T extends (infer U)[] ? U : T;
type Foo = Unpacked<FILTER_META['filters']>;
// how to determine comparer type from meta object
// comparer:Foo doesn't work
// const comparator = <T extends FILTER_META, U extends Unpacked<T['filters']>>(
const comparator = (meta: FILTER_META, item: any, comparer: any) => {
const DATE_PREFIX = '1/1/2022 ';
switch (meta.type) {
case
return item?.[meta.key]?.toLowerCase() === comparer.id?.toLowerCase();
case 'time': {
const { min, max } = comparer;
const compTime = new Date(DATE_PREFIX + item?.[meta.key]);
return (
new Date(DATE_PREFIX + min) <= compTime &&
compTime <= new Date(DATE_PREFIX + max)
);
}
case 'range': {
const { min, max } = comparer;
const compItem = item?.[meta.key];
return min <= compItem && compItem <= max;
}
}
};
const genericFilter =
(filterMeta: FILTER_META[]) =>
(list = []) =>
list.filter((item) =>
filterMeta
.filter((fMeta) => fMeta.filters.length)
.every((meta) =>
meta.filters.some((ft: any) => comparator(meta, item, ft))
)
);
This is a versatile filtering function that aims to sort an array using various filter types. It receives an assortment of different filters in an array and employs the comparer function to execute the filtering.
How can I specify the type of the third argument comparer:any
based on the first argument which is of type FILTER_META
Find the code on Stackblitz via the following link: https://stackblitz.com/edit/typescript-ku6bq7