Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown:

export interface ProductsList {
   id: boolean
   nome: string
   qtde: number
   valor: number
   valorTotal: number
}

const exampleFn = (productsData: ProductsList[], order: string) => {
   if (order !== 'id' && order !== 'nome') {
        productsData.sort((a, b) => b[order] - a[order])
   }
}

The error message related to order reads as follows:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProductsList'.
  No index signature with a parameter of type 'string' was found on type 'ProductsList'

I have attempted adding an index signature to order, but unfortunately, it did not solve the issue.

Any insights or suggestions on what might be causing this problem?

Answer №1

When trying to subtract a string or boolean, it doesn't make sense. Instead, you should utilize keyof and an exclude:

export interface ProductsList {
   id: boolean
   nome: string
   qtde: number
   valor: number
   valorTotal: number
}

const exampleFn = (productsData: ProductsList[], order: Exclude<keyof ProductsList, 'id'| 'nome'>) => {
   productsData.sort((a, b) => {
       const c = a[order]
       return b[order] - a[order]
       })
}

update: By using the key check, you can actually avoid the need for exclude!

const exampleFn = (productsData: ProductsList[], order: keyof ProductsList) => {
   if (order !== 'id' && order !== 'nome') {
      productsData.sort((a, b) => {
         const c = a[order]
         return b[order] - a[order]
      })
   }
}

playground

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

Adjust the horizontal position of the background by +/- X pixels

Is there a way to adjust the background-position by a specific distance, say 20px, from its original position? For example: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (Unfortunately, this approach doesn't yield the d ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

When using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

The image in drag and drop ghost preview is not appearing on Firefox

I want to show a ghost element instead of the default browser preview while dragging and dropping. However, in Firefox, the image inside the ghost element is not displayed during dragging. Oddly enough, if I drop it and then drag again, the image does appe ...

Displaying URLs stylishly with Pills Bootstrap

When a pill is selected from the list, I need to display a specific URL that can be used elsewhere. However, there is an href="#pills-something" attribute that directs to an ID below. I am looking for something like: mysite.com/myspecificpill or ...

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). https://i.sstatic.net/NcJWU.png ...

Tips for customizing table cell styling in editable cells with React material table

My code utilizes a material table with editable cells. However, I am encountering a strange style issue when I edit a cell in the table. Please refer to the image below. Can anyone suggest a solution to fix this problem? https://i.sstatic.net/Miiov.png ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Tips for incorporating validation/restrictions into react-datepicker

I've been working on implementing restriction and validation in a react-datepicker component. I'm utilizing redux-form for validation and normalization purposes. Issue: I've noticed that neither the normalizing function nor the validation f ...

Strategies for managing the fallback scenario while utilizing 'createReducer' to generate a reducer and 'on' to manage actions

In the past, our reducers were created like this before the createReducer helper method was introduced: export function reducer(state: AppState, action: Action) { switch (action.type) { case "[Category List] Add Category": return { . ...

Step by step guide to implementing form step validation in a multi-step jQuery form with radio buttons

I have implemented the sample code provided in this link, with the addition of 2 extra form steps: LINK TO SAMPLE FORM My form consists of radio buttons (2 per page) instead of text boxes. How can I ensure that each form page is validated so that the for ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Issues arise when trying to use Prettier and ESlint in conjunction with one another

It appears that prettier is not formatting the code as desired. Here is my current ESLint configuration: "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ &q ...

What are the ways to change a PDF file or web address into a DOCX document using NodeJS?

I've been doing some research on converting URLs to DOCx or PDF to DOCx in NodeJS, but I haven't found a proper solution yet. I tried reaching out to PhantomJS, but it only converts URLs to PDF. Do you have any idea if PhantomJS can convert to D ...