I'm working with an array of objects that need to be sorted based on specific criteria. The goal is to sort the array by descending order of holiday_for if the holidays have the same holiday_on date.
const holidays: IHoliday[] = [
{
id: 1,
holiday_for: 1,
holiday_on: "2021-10-26"
},
{
id: 2,
holiday_for: 3,
holiday_on: "2021-10-26"
},
{
id: 3,
holiday_for: 1,
holiday_on: "2021-11-26"
},
{
id: 4,
holiday_for: 3,
holiday_on: "2021-11-26"
},
{
id: 5,
holiday_for: 4,
holiday_on: "2021-11-26"
}
]
However, I encountered a type error in my current implementation. It says
Argument of type '(a: IHoliday, b: IHoliday) => number | undefined' is not assignable to parameter of type '(a: IHoliday, b: IHoliday) => number'. Type 'number | undefined' is not assignable to type 'number'
If I try changing the holidays array to any type to resolve this issue, TypeScript throws another warning -
Not all code paths return a value.
Here's how I tried implementing the sorting logic:
const sorted = holidays.sort((a: IHoliday, b: IHoliday) => {
if (a.holiday_on === b.holiday_on) {
return b.holiday_for - a.holiday_for;
}
});