Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Use generic Types! #74

Open
btxtiger opened this issue Dec 22, 2021 · 1 comment
Open

Use generic Types! #74

btxtiger opened this issue Dec 22, 2021 · 1 comment

Comments

@btxtiger
Copy link

Can you use generic types instead converting the whole data object to type any. Otherwise all TypeScript information about the object properties will be lost!

Here is my implementation:

   /**
    * Search Filter Pipe
    * @param items object from array
    * @param term term's search
    * @param excludes array of strings which will ignored during search
    */
   public transform<T>(items: T[], term: string, excludes: any[] = []): T[] {
      if (!term || !items) return items;

      return SearchFilterPipe.filter(items, term, excludes);
   }

   /**
    * Filer items[]
    * @param items List of items to filter
    * @param term  a string term to compare with every property of the list
    * @param excludes List of keys which will be ignored during search
    */
   private static filter<T>(items: T[], term: string, excludes: any[]): T[] {
      const toCompare = term.toLowerCase();

      /**
       * Check filterable object props
       */
      function checkInside(item: any, term: string): boolean {
         if (typeof item === 'string' && item.toString().toLowerCase().includes(toCompare)) {
            return true;
         }

         for (let property in item) {
            if (item[property] === null || item[property] == undefined || excludes.includes(property)) {
               continue;
            }
            if (typeof item[property] === 'object') {
               if (checkInside(item[property], term)) {
                  return true;
               }
            } else if (item[property].toString().toLowerCase().includes(toCompare)) {
               return true;
            }
         }
         return false;
      }

      return items.filter(function (item) {
         return checkInside(item, term);
      });
   }
@aVolpe
Copy link
Collaborator

aVolpe commented Dec 22, 2021

@btxtiger you can also type excludes using k: Array<keyof T> (or string[]).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants