I'm trying to write a function to sort various arrays on object, based on a key. Here's my code :
const sort = (value: keyof TargetTypes) => {
const sortedTargetsList = targetsList && [...targetsList]
sortedTargetsList?.sort((a, b) => a[value].localeCompare(b[value]))
}
Then I've an error hovering localeComparesaying (Google Trad) :
Property 'localeCompare' does not exist on type 'string | boolean | string [] | [] | {platform: string; link: string; userId: string; } [] '.
Property 'localeCompare' does not exist on type 'false' .ts (2339)
Tried various things but can't find a way or even understand what's going wrong. I've tried by hard coding the value like so, and it works : a['targetName']
Thanks for your help guys.
Resolved by doing this, not sure if it's the better way... Kinda didn't like the eslin disable line but I don't have any clues..
const sort = (value: keyof TargetTypes) => {
setTargetsList(
targetsList &&
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[...targetsList].sort((a: any, b: any) =>
a[value].localeCompare(b[value]),
),
)
}
I prefered this solution over the @shobe one just because it give me suggestions after typing "sort(" to select an available key.