1

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?

8
  • What are the acceptable values of order? It's not an arbitrary string, but specifically those keys of ProductsList that have a number-valued property, like this, right? If so I could write up an answer; if not, what am I missing? Commented Jul 6, 2022 at 22:07
  • 2
    Please replace/supplement images of code/errors with plaintext versions. Commented Jul 6, 2022 at 22:08
  • @jcalz that's right, the value are the same as the keys. Commented Jul 6, 2022 at 22:10
  • subtracting boolean or string doesn't make sense. Commented Jul 6, 2022 at 22:11
  • 1
    Okay, I'll write up an answer when I get the chance (unless someone else gets here first) Commented Jul 6, 2022 at 22:11

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.