简体   繁体   English

TypeScript 比较函数参数的类型

[英]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我正在声明一个 function 用于sort方法,该方法采用对象数组的值并将其与另一个对象数组进行比较

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:但我在 TypeScript 上这样做,我在 TypeScript 上很新,但我不敢相信我必须这样声明参数:

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 TypeScript 游乐场

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) =>... @Chase指出有一个简写我可以使用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指出我正在使用sort方法改变我没有注意到的原始array

@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. @jcalz还以更实用的方式重构了代码,并指出如果sort方法是内联的,则会推断出它们的参数类型。 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最后我使用了@jcalz 方法并做了这个

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 TypeScript 游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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