The fixture script from the last exercise runs in Node.js as it is. The results table is next. The league’s website wants it sorted by points for the standings page and by name for the club directory. One method that takes the comparison as a function covers both, and that function needs a type.
In this lesson, you’ll write types for functions you pass as values. You’ll use one to catch a bug in a comparator that a helper suggested, and you’ll see why a callback that returns a value can still fit a type that promises nothing. Start with what a comparison takes and gives back.
Write a Function Type
A method that takes a function has to say what that function receives and what it must return. Start with the JavaScript. Open the results-table.ts file you typed in the first lesson and add this method to the class, below .standings():
sortedBy(compare) {
return this.rows.toSorted(compare);
}
The method hands compare straight to .toSorted(), so the caller picks the order. For the standings page, that’s table.sortedBy((a, b) => b.points - a.points), most points first.
The call shows what compare must be. The .toSorted() method calls it with two rows and reads the number it returns. A negative number puts the first row ahead, a positive one puts the second row ahead, and zero keeps their order.
Nothing in the code says so yet. Run npm run check, and strict mode reports Parameter 'compare' implicitly has an 'any' type. The checker can’t tell which functions the method accepts, so write that down as a type. Add this line below TeamRow:
type CompareRows = (a: TeamRow, b: TeamRow) => number;
The right-hand side is a function type expression. It looks like an arrow function with a type where the body would be. Inside the parentheses, each parameter has a name and a type, and after the => comes the return type. It only describes a function, so nothing runs, and Node.js strips it with the other types.
The names a and b are there for the reader. A function whose parameters have other names still fits, as long as the rows it’s given suit its parameters and it returns a number.