Fabio Montone
Fabio Montone

Reputation: 49

React Typescript Custom Hook Sort List

I'm trying to create a custom hook in react to return a sorted array based on two arguments: the list itself and a string with the key I want to sort. Just tried several strategies before asking how to solve that, lot's of hours cursing TS, but still have the faith it has a simple solution I'm not seeing.

the Hook:


type Item = {
  [key: string]: number | string,
}

function useSortList(list: Item[], key: string) {

  return list.sort((a: object, b: object) => a[key] > b[key] ? 1 : -1) || list;

}

export default useSortList;

On a[key] > b[key] I'm getting this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)

I.e.: I'm passing as list a simple movies array of objects and trying to sort this by 'title'.

How could I type this sort parameters so I can use this with any array of objects?

Cheers!

Upvotes: 0

Views: 718

Answers (1)

Parzh from Ukraine
Parzh from Ukraine

Reputation: 9873

That's because you are using object type. Try removing this type annotation.

Since the type of list variable is well defined, list.sort is well defined as well, no need to try and help TypeScript with this (see).

Upvotes: 1

Related Questions