Writing Generic Types

Your lookup helpers now work for any league record and hand back the caller’s own type. The client’s replies have a duplication problem, though. Each script that fetches spells out its own reply type for its endpoint. Collected in one place, the three look like this, differing only in their names and the element type in data:

Language: TypeScript
export type TeamsReply =
  | { ok: true; data: Team[] }
  | { ok: false; error: string };

export type PlayersReply =
  | { ok: true; data: Player[] }
  | { ok: false; error: string };

export type FixturesReply =
  | { ok: true; data: Fixture[] }
  | { ok: false; error: string };

Each one is a discriminated union: checking ok tells the checker which branch you have. In this lesson, you’ll write that shape once as a generic type and fill it in for each endpoint. You’ll also see why its type parameter can never do anything at runtime. Start with the copies.

Write the Reply Type Once

Three copies can drift apart: if the API adds a status to its errors, someone must update all three. A type parameter fixes this the way it did in first<T>(): you name the part that changes and write the rest once.

Instead of adding three copies to types.ts, add this one type:

Language: TypeScript
export type ApiResult<T> =
  | { ok: true; data: T }
  | { ok: false; error: string };

This is a generic type: a type alias with a type parameter after its name. On its own, ApiResult isn’t a finished type yet. You fill in T where you use it, as you’ve done with Promise<Player[]> and Map<number, Team>.

Scripts that want a name for each endpoint still get one, each a filled-in ApiResult. Add these lines below it:

Language: TypeScript
export type TeamsReply = ApiResult<Team[]>;
export type PlayersReply = ApiResult<Player[]>;
export type FixturesReply = ApiResult<Fixture[]>;

To see it at work, create shirts.ts. It’s a toy that turns a reply containing players into a line for the kit volunteer, with two players typed in where the client would fetch them:

Language: TypeScript Filename: shirts.ts
import type { ApiResult, Player } from "./types.ts";

function shirtList(result: ApiResult<Player[]>): string {
  if (!result.ok) {
    return `No players: ${result.error}`;
  }
  return result.data
    .map((player) => `${player.shirt} ${player.name}`)
    .join(", ");
}

const reply: ApiResult<Player[]> = {
  ok: true,
  data: [
    { id: 1, name: "Amara Diallo", shirt: 9, teamId: 1 },
    { id: 2, name: "Leo Brennan", shirt: 1, teamId: 1 },
  ],
};
console.log(shirtList(reply));
console.log(shirtList({ ok: false, error: "Not found" }));

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.