Typescript Type for a Compare Function's Parameters

I am declaring a function to use on a sort method that takes the value on an array of objects and compares it against another array of objects

const compare = (a, b) => {
  let x = 0
  let y = 0
  RoleIndex.forEach(({ role, id}) => {
    if (role.includes(a.role)) x = id
    if (role.includes(b.role)) y = id
  })

  if (x > y) return 1
  else return -1
})

But I am doing this on TypeScript, I am quite new at TypeScript but I can not believe I have to declare the parameters this way:

const compare = ((a: { role: string}, b: { role: string}) => {
  let x: number = 0
  let y: number = 0
  RoleIndex.forEach(({ role, id}) => {
    if (role.includes(a.role)) x = id
    if (role.includes(b.role)) y = id
  })

  if (x > y) return 1
  else return -1
})

Is there a simpler way?

Here is the whole code of what I am trying to do:

TypeScript Playground

10

1 Answer

Thanks for the comment responses.

@Chase pointed out there is a shorthand I could use const compare<T extends { role: string }>(a: T, b: T) =>...

But more importantly @jcalz pointed out I was mutating the original array which I did not notice, with the sort method.

@jcalz also refactored the code in a much more functional way, and pointed out that if the sort method is inline their parameters types are inferred. So this a much better approach. Not only I don't have to declare the types but is not mutating the original array and it's a lot more readable.

In the end I used @jcalz approach and did this

const sortedArray = array
  .map(employee => ({
    ...employee,
    id: RoleIndex.find(({ role }) => role.includes(employee.role)) ?. id ?? 100
  }))
  .sort((a, b) => a.id - b.id)

TypeScript Playground

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest