Reading Types Off Functions

In the last lesson, you derived the create and update types from Team, so the forms follow it. The newsletter script still has a hand-copied type, though. It describes the standings returned by buildTable(), the function the league table uses. If someone adds goal difference to the table, that copy goes stale without a word from the checker.

In this lesson, you’ll read types straight off functions with four more utility types. You’ll be able to name the types of a function’s result and parameters, unwrap what an async function resolves to, and drop undefined from a lookup’s result. Start with the table builder.

Read a Function’s Result and Parameters

A function already states what it takes and what it returns, so a second copy of either can fall out of step with it. The builder below imports MatchResult from results-table.ts, which doesn’t export it yet. In that file, add export in front of type MatchResult.

Then replace the table.ts from Deriving Types With keyof and typeof with the builder that the league table and the newsletter share:

Language: TypeScript Filename: table.ts
import type { MatchResult } from "./results-table.ts";

function score(scored: number, conceded: number): number {
  if (scored > conceded) return 3;
  return scored === conceded ? 1 : 0;
}

export function buildTable(
  teams: string[],
  results: MatchResult[],
): { team: string; points: number }[] {
  const rows = teams.map((team) => ({ team, points: 0 }));
  for (const { home, away, homeGoals, awayGoals } of results) {
    for (const row of rows) {
      if (row.team === home) row.points += score(homeGoals, awayGoals);
      if (row.team === away) row.points += score(awayGoals, homeGoals);
    }
  }
  return rows.toSorted((a, b) => b.points - a.points);
}

Then create newsletter.ts, which takes both of its types from buildTable():

Language: TypeScript Filename: newsletter.ts
import { buildTable } from "./table.ts";

type Standings = ReturnType<typeof buildTable>;
type TableInput = Parameters<typeof buildTable>;

function tableLines(standings: Standings): string {
  return standings
    .map((row, i) => `${i + 1}. ${row.team} ${row.points}`)
    .join("\n");
}

const week3: TableInput = [
  ["Riverside Lions", "Kestrel Park", "Mill Lane Otters"],
  [
    {
      home: "Kestrel Park", away: "Riverside Lions",
      homeGoals: 1, awayGoals: 3,
    },
  ],
];
console.log(tableLines(buildTable(...week3)));

Utility types take types, and buildTable is a value, since functions are values in JavaScript. So typeof buildTable reads the function’s type first, as typeof did for the age group list. ReturnType gives the type of the array of rows. Parameters gives the parameters’ types as a tuple, labeled with the parameter names:

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

Become a Member to join the conversation.