Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

75
Visualizações
Using localCompare with key passed in a function

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda