Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

TypeScript type for a compare function's parameters

Writer Sebastian Wright

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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