简体   繁体   中英

Sort array of objects in typescript - element implicty has any type

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM