Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Keeping the Type With Generic Functions

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

  • any loses the type on the way out. The awards script’s first(items: any[]): any passes 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, T is a name for a type that each call fills in. The return type includes undefined because an empty list has no first item.
  • The checker fills in T from the argument. first(scorers) passes a string[], so T is string and topRate is string | undefined. Now npm run check finds 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) makes T number. With the log inside if (topRate !== undefined), the check is clean and Node prints Golden 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, run node server.mjs and 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 for T. The reply starts as unknown. If isT rejects it, request() throws. Past the check, the reply is a T, and request() returns it, wrapped in a promise.
  • T follows the guard to the result. request("/players", isPlayerList) matches isPlayerList, whose return type is value is Player[], against isT, so T is Player[]. The result is a Promise<Player[]>, and await unwraps it, so players is a Player[].
  • T is erased, and the guard runs. When Node runs the file, T is gone with the other types, but isT(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:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 The league’s scripts all paste in the same small helpers. In this video, you’ll make them keep the type you pass in. Here’s a toy version of the season awards script.

00:11 Its helper, first, returns the first item of a list. Both its types say any, so it takes a list of anything.

00:19 The names and the goals per game are the top scorers, best first. The script wants the best rate, to one decimal place.

00:29 Look at the call on line 8. It passes the names where it meant the rates. Your turn: pause the video and predict whether npm run check catches the slip.

00:45 The check comes back clean. Run the script with Node, and it crashes. toFixed is not a function.

00:54 topRate holds Amara’s name, and a string has no toFixed method. The helper returns any for every list, so the list’s type is lost on the way out. And any turns off checking for topRate, so toFixed gets through.

01:11 You want the first helper to return the type of item that goes in. Add a T in angle brackets after the name. T is a type parameter, a name for a type that each call fills in.

01:24 The parameter becomes a list of T. The return type becomes T or undefined, because an empty list has no first item. Your turn: pause the video and predict the type that topRate gets now.

01:43 It’s string or undefined. The checker reads the argument, a list of strings, so string fills in T for this call. T goes where the return type has it, and topRate gets that.

01:57 Run the check again, and it reports two errors on line 9. The second says toFixed doesn’t exist on type string. That’s the slip, found before anything runs.

02:09 Ignore its hint, an old method. The first error says topRate is possibly undefined, the empty list case. Pass the rates instead, and number fills in T. Check topRate isn’t undefined first.

02:25 Now the check is clean. Node prints 1.5 goals a game.

02:33 The certificates script, another toy, pastes in a request helper to fetch the players from the league’s API. The course’s download has a stand-in for that API.

02:44 The script’s guards file is below the video. In a second terminal, in the project folder, run node server.mjs, and leave it running. This request returns a promise of any, so players is any, and each player too.

03:00 The script runs, but nothing checks what it reads.

03:05 The first helper got its type from the list. A request has only a path, which doesn’t say what the reply holds. And the reply only arrives at run time, so it needs a check there.

03:17 So the caller passes a check in. Add T to request, and it now promises a T. The second parameter is the check, a function that takes an unknown value. Its return type, value is T, makes it a type guard.

03:34 The reply starts out unknown. If the check rejects it, request throws. Past the check, the reply is a T, and request returns it.

03:44 The call passes isPlayerList, a type guard from the guards file. It says the value is a list of players. Now follow T. The checker matches isPlayerList against the check parameter, so T is a list of players.

04:00 T goes into the promise, await unwraps it, and players is a list of players. When Node runs the file, T is gone with the other types, but the guard stays and checks the reply.

04:12 Node prints a certificate for each player.

04:17 Here’s the rule: when a function’s result has the type of what the caller passes in, give it a type parameter. With any, that type is lost. With T, it comes out the other side, for the checker to use.

04:32 Next, in Constraining a Type Parameter, you’ll write a lookup by ID, where T has to promise it has one.

Become a Member to join the conversation.