Creating a custom data type for the Tanstack table filtering function

I developed a unique filter function specifically for enhancing the functionality of Tanstack Table by utilizing fuse.js.

Despite my efforts, TypeScript consistently raises concerns when I try to define the type for my custom function.

My goal is to align my Function with the following type definition:

export interface FilterFn<TData extends RowData> {
    (row: Row<TData>, columnId: string, filterValue: any, addMeta: (meta: FilterMeta) => void): boolean;
    resolveFilterValue?: TransformFilterValueFn<TData>;
    autoRemove?: ColumnFilterAutoRemoveTestFn<TData>;
}

This piece of code showcases my function. I aspire to utilize TData instead of any but find myself uncertain about the exact approach.

/**
 * Custom FilterFunction designed for Tanstack Table integrating fuse's fuzzy search capability
 */
export const fuseFilterFn: FilterFn<any> = (
  row,
  columnId,
  filterValue,
  addMeta
) => {
  const searchPattern = filterValue.toString();

  const fuse = new Fuse([row.getValue(columnId)]);
  const searchResults = fuse.search(searchPattern);

  if (searchResults.length > 0) {
    // If any search result is found, mark the row as a match
    addMeta({ searchResults }); // Optionally, include metadata related to the search results
    return true;
  }

  return false;
};

The following snippet illustrates the structure of my table

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  columnFilters?: ColumnFilter[];
}

export function Table<TData, TValue>({
  data,
  columns,
  columnFilters = [],
}: DataTabelProps<TData, TValue>) {
  const [sorting, setSorting] = useState<ColumnSort[]>([]);
  const [filtering, setFiltering] = useState('');

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    state: {
      sorting: sorting,
      globalFilter: filtering,
      columnFilters: columnFilters,
    },
    globalFilterFn: fuseFilterFn,
    onSortingChange: setSorting,
    onGlobalFilterChange: setFiltering,
  });

Answer №1

If you don't want it to be of type Any, you need to specify the type.

For example:

/**
* Define your custom type here.
*/
type YourGenericTypeHere = {
  stringprop: string,
  numprop: number,
  recordprop: Record<string,any>,
  optional?: string,
  objectprop: Object
}

// Define columnDefinition using the type previously defined
export const columns: ColumnDef<YourGenericTypeHere>[] = [{
id: "someidyouchose",
header: ({table}) => (<CustomHeaderElement/>),
// ... etc
}]
/**
 * 
 *
 * Pass the Type definition to the filter function as well, so we can filter correctly
 */
export const fuseFilterFn: FilterFn<YourGenericTypeHere> = (
  row,
  columnId,
  filterValue,
  addMeta
) => {
  const searchPattern = filterValue.toString();

  const fuse = new Fuse([row.getValue(columnId)]);
  const searchResults = fuse.search(searchPattern);

  if (searchResults.length > 0) {
    // If any search result is found, consider the row as a match
    addMeta({ searchResults }); // Optionally, add any metadata for the search results
    return true;
  }

  return false;
};

When rendering the table, make sure to pass the imported column prop with the correct data type YourGenericTypeHere.

<DataTable data={data} columns={columns} />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Executing one controller function from another controller in Typescript

There are two typescript controllers in my project Controller A { public methodOfA() {//perform some action} } Controller B { public methodOfB() {//perform some action} } I am trying to implement the following functionality Controller B { ...

`Why TypeScript in React may throw an error when using a setter`

As I work on building a small todo app in TypeScript with React, I encountered an issue when attempting to add a new todo item to my list. It seems like the problem may lie in how I am using the setter function and that I need to incorporate Dispatch and s ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Utilizing Radio buttons to establish default values - a step-by-step guide

I am utilizing a Map to store the current state of my component. This component consists of three groups, each containing radio buttons. To initialize default values, I have created an array: const defaultOptions = [ { label: "Mark", value: & ...

Sort attributes by the type of property

Is there a way to create a customized type by extracting specific properties from a generic type? class Test { value1!: Date value2!: number value3!: Date value4!: string } type FilterProperties<T, TFieldType> = //looking for a solution to se ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

Implement a click event listener in React.js

How can I implement a callback function for button clicks in my TypeScript code? This is the code snippet: export enum PAYMENT_METHOD { online, offline, } interface Props { paymentMethod: PAYMENT_METHOD; togglePaymentMethod: (paymentMethod: PAYM ...

Ways to solve VScode gutter indicator glitches after switching text editors?

When my active function is running, I have a specific updateTrigger that ensures certain actions are taken when the activeTextEditor in vscode changes: const updateTrigger = () => { if (vscode.window.activeTextEditor) { updateDecorations(con ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Struggling to integrate D3.js with React using the useRef hook. Any suggestions on the proper approach?

I'm currently working on creating a line chart using d3.js and integrating it into React as a functional component with hooks. My approach involved utilizing useRef to initialize the elements as null and then setting them in the JSX. However, I encou ...

Angular 2- Unable to bind to 'ngSwitchCase' as it is not recognized as a native property

I am facing an issue with my code where I have two lists that are displayed in my .html file. In order to avoid repetition, I decided to utilize ngSwitch. However, when I try to implement this approach, I encounter an error. Here is the snippet of code cau ...

Refresh a doughnut chart in real-time using NG2Charts

Currently, I am in the process of developing a macronutrient calculator as part of a project. The idea is to have a form where users can input values, and a corresponding doughnut chart will display with initial values set at 0. However, upon clicking the ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Creating TypeScript versions of `delegate` pattern JavaScript code

Looking for a way to convert the following javascript code into typescript? const handlers = { say (msg) { console.log(msg) }, add (a, b) { return a + b } } function caller (method, ...args) { if (handlers[method]) return handlers[methd ...