The method 'toLowerCase' is not present on the specified type 'T[keyof T]'

I'm currently working on a function that uses generic types to take two arguments (an array of objects and a search term), but I keep encountering an error - The property 'toLowerCase' is not available on the type 'T[keyof T]'

Here's the function:

function findMatchingTerms<T>(data: T[], searchTerm: string): T[] {
  return data.filter((obj) => {
    const filteredData = (Object.keys(obj) as Array<keyof typeof obj>).some((value) => {
      return (
        typeof obj[value] === "string" && obj[value].toLowerCase().includes(searchTerm.toLowerCase())
      );
    });
    return filteredData;
  });
}

What am I missing here?

Answer №1

This solution seems to be addressing a similar issue mentioned in this link: https://github.com/microsoft/TypeScript/issues/10530

To improve type inference, it is suggested to extract obj[value] into a variable as shown below:

function matchSearchTerm<T>(data: T[], search: string): T[] {
  return data.filter((obj) => {
    const filteredData = (Object.keys(obj) as Array<keyof typeof obj>).some((value) => {
      const val = obj[value];
      return (
        typeof val === "string" && val.toLowerCase().includes(search.toLowerCase())
      );
    });
    return filteredData;
  });
}

Answer №2

What do you think of this approach:

return obj[value]['toLowerCase']?.call(obj[value]).includes(search.toLowerCase())

From my perspective, it seems to be returning either true, false, or undefined. This is suitable for filters in my opinion. Alternatively, we could use a ternary operator if we only want a true/false outcome.

Answer №3

function filterBySearchTerm<T extends Record<string, string>>(items: T[], term: string) {
  return items.filter((item) => {
    const filteredItem = (Object.keys(item) as Array<keyof T>).some((value) => {
      const checkValue = item[value]
      return (
        typeof item[value] === "string" && item[value].toLowerCase().includes(term.toLowerCase())
      );
    });
    return filteredItem;
  });
}

Enhance the T generic type with an additional constraint:

T extends Record<string, string>

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

Why is my showMap() function not executing when the button is clicked? How can I resolve this issue in JavaScript?

Why isn't the JavaScript code for showMap() running? How can this issue be resolved? <html> <title></title> <script> function showMap() { alert("rong"); } fun ...

Incorporate the operating hours of a Business

If I specifically choose Sunday and Monday with working hours ranging from 08.00 to 20.00, the output should be 1&08:00&20:00,2&08:00&20:00. How can I achieve this using Vue.js? This is my current code: <script> submitBox = new Vue( ...

Using JQuery to test for element visibility in Jest tests

I am currently facing an issue in my unit test where the visibility state of an element does not change as expected. I am using .is(":visible") to verify this, and while it works fine in browsers, the unit test always reports that the element is hidden. B ...

Transforming a string into key-value pairs using Typescript

Is there a way to transform the given string into key-value pairs? TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false ...

I have a task that requires me to click on the 'OK' button within an ALERT pop-up while using Selenium on Internet Explorer

Clicking on the 'OK' button from an alert on Internet Explorer seems to be giving me trouble. I've attempted using drive.switch_to.alert().accept()/.send_keys(Keys.ENTER) with Selenium Webdriver in Python, but it doesn't seem to be work ...

Error: The callback specified is not a valid function

Here is a function example: reportAdminActions.reportMemberList(project, function(data) { console.log(data); }); This particular function gets called by another ajax operation, similar to the one shown below: reportMemberList: function(projectId, ca ...

How to Implement Search Functionality in a Multiple Select Dropdown using Select2 Plugin in VueJS

I'm currently using the Select2 component from VueJS https://www.npmjs.com/package/vue-select2 import VueSelect2 from "vue-select2"; https://i.sstatic.net/MvJVw.png I am interested in adding an option to search within the displayed list it ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...

Verify whether the div already includes a particular item

I am currently working on an angular project where I need a button to add a blockquote within a div, but only if the blockquote is not already present in the HTML structure. My initial approach was to search for the specific string <blockquote id=&apos ...

Trigger pipeline to terminate on identification of dependencies by npm audit

I'm currently using npm audit in my GitLab CI pipeline, and it's working well. I have a JSON file that lists the dependencies needing updates. Now, I'd like the pipeline to fail whenever a dependency is outdated. In other languages, such ...

JS Unable to get scrollIntoView function to work with mousewheel event

I have been working with the script provided above. It correctly displays the id in the browser console, but unfortunately, it is not triggering the scrolling function as expected. var divID = null; var up = null; var down = null; function div(x) { s ...

Tips for preventing errors in JavaScript date formatting

Currently, I am utilizing the DHTMLX Scheduler within my web application and aiming to access data for each event. Fortunately, I discovered a method to achieve this using scheduler._events which provides the following information: 1581498064943: {…} ​ ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Utilizing numpy for modifying a binary vector

If I have a function that generates a list of non-unique indices between 0 and (n-1), where n represents a user-defined value, there are certain interpretations to be made based on the generated array. Let's assume for simplicity that n is 5. #arr = m ...

Can someone guide me on how to organize a div structure into a table format with the help of JQuery

I am new to JQuery and I have created a table using divs instead of the traditional table structure. Each row has the same ids, which I thought would help me sort the table. Here's an example of my code: <div class="column_title">Column 1</ ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

Combining httpProvider responseInterceptor with $http error callback does not function properly

In my application, I implemented a "loading screen" feature inspired by this post: 'Click' However, I am facing an issue where all $http requests are triggering the "success" callback, even for URLs that do not exist. $http.post("this doesnt ev ...

The z-index property in jQuery dialog does not seem to function properly when used within an

When using bootstrap with jQuery dialog, I encountered a strange issue. If the z-index of the dialog is set to 1 or higher in a standalone script, everything works fine. However, when the same script is called inside an iframe, the dialog ends up appearing ...

Error Message: "Issue with jQuery mobile: Uncaught TypeError - Unable to read property 'abort' of undefined during AJAX request"

Hey there, I recently created a website using jQuery Mobile and implemented the autocomplete feature. However, I encountered an error message saying Cannot read property 'abort' of undefined. Here is the code snippet: <div id="myPage"> ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...