简体   繁体   中英

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

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

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