Home > front end >  Sort array of objects in typescript - element implicty has any type
Sort array of objects in typescript - element implicty has any type

Time:07-07

I'm trying to sort an array of objects within a function, however the function receives the key as a parameter, so it's 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])
   }
}

I'm getting this error with order:

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've tried to set an index signature to order, but without success.

What can it be?

CodePudding user response:

Since substracting string or boolean makes no sense, you should use 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]
       })
}

edit : With the key check, you can also skip the 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

  • Related