I have tuples in the form (Status and priority)
[State,prio]
States are defined so:
enum State {
A = "A",
B = "B",
C = "C"
...
}
Now i want to sort an array of State tuples by priority using the sort function:
compareFn(a:[State,number], b:[State,number]):number {
if (a[1] > b[1]) {
return -1;
} else if (a[1] < b[1]) {
return 1;
}
return 0;
}
This is the array:
let prio = [
[State.A, 23],
[State.B, 2],
[State.C, 5]
]
When invoking the array sort function with the compareFn callback
prio.sort(compareFn)
the following error is given:
Argument of type '(a: [State, number], b: [State, number]) => number' is not assignable to parameter of type '(a: (number | State)[], b: (number | State)[]) => number'. Types of parameters 'a' and 'a' are incompatible. Type '(number | State)[]' is not assignable to type '[State, number]'.
I have no idea where this data type comes from and how to resolve this:
(number | State)[]
Any ideas?
Answer by @nseaprotector is correct. You could also inline the compare directly if you prefer, see below:
enum State {
A = "A",
B = "B",
C = "C"
}
const prio: [State, number][] = [
[State.A, 23],
[State.B, 2],
[State.C, 5]
];
prio.sort((a, b) => b[1] - a[1]);
console.log(prio);