In this video, you took two helpers that the league’s scripts paste in, first() and request(), and gave each a type parameter, so what comes out has the type of what the caller passed in. Both scripts are toys, cut down to show the helpers.
Key Points
anyloses the type on the way out. The awards script’sfirst(items: any[]): anypasses the check even when the call hands it the players’ names instead of their goals per game. Nothing checks the result, so Node crashes when the script formats a name as a number:TypeError: topRate.toFixed is not a function.- A type parameter names the caller’s type. In
function first<T>(items: T[]): T | undefined,Tis a name for a type that each call fills in. The return type includesundefinedbecause an empty list has no first item. - The checker fills in
Tfrom the argument.first(scorers)passes astring[], soTisstringandtopRateisstring | undefined. Nownpm run checkfinds the slip before anything runs: error TS2551, “Property ‘toFixed’ does not exist on type ‘string’”, and TS18048, “‘topRate’ is possibly ‘undefined’”. - Pass the right list, and handle the empty case.
first(goalsPerGame)makesTnumber. With the log insideif (topRate !== undefined), the check is clean and Node printsGolden boot: 1.5 goals a game. - Start the league’s stand-in API before a script fetches from it. The stand-in,
server.mjs, comes with the Riverside project in the course’s Sample Code (.zip) download. In a second terminal, in the project folder, runnode server.mjsand leave it running. - A request has only a path, so the caller passes the check in.
request<T>(path: string, isT: (value: unknown) => value is T): Promise<T>takes a type guard forT. The reply starts asunknown. IfisTrejects it,request()throws. Past the check, the reply is aT, andrequest()returns it, wrapped in a promise. Tfollows the guard to the result.request("/players", isPlayerList)matchesisPlayerList, whose return type isvalue is Player[], againstisT, soTisPlayer[]. The result is aPromise<Player[]>, andawaitunwraps it, soplayersis aPlayer[].Tis erased, and the guard runs. When Node runs the file,Tis gone with the other types, butisT(reply)still checks the reply.- The rule: when a function’s result has the type of what the caller passes in, give it a type parameter.
The Code
The awards script, with first() keeping the type of the list: