Constraining a Type Parameter

The last video gave the certificates script a request() function that hands back the caller’s type. Here’s that function again, for reference, from certificates.ts:

Language: TypeScript
async function request<T>(
  path: string,
  isT: (value: unknown) => value is T,
): Promise<T> {
  const response = await fetch(API + path);
  const reply: unknown = await response.json();
  if (!isT(reply)) {
    throw new Error(`Unexpected reply from ${path}`);
  }
  return reply;
}

The checker fills in T from the guard you pass. In this lesson, you’ll see what happens when a call provides nothing to infer T from. Then you’ll write a lookup that needs every item to have an id, and you’ll tell the checker so.

Write Out a Type Argument

A generic function takes type arguments the way Map does. To try one, add import type { Player, Team } from "./types.ts"; to certificates.ts. Then request<Player[]>("/players", isPlayerList) means the same as the call without the angle brackets, and the checker still validates the call. Write Team[] there instead, and error TS2345 ends in Type 'Player' is missing the following properties from type 'Team': ageGroup, coach.

The loop’s player.shirt gets its own error too, since players is now Team[]. Put the call back to request("/players", isPlayerList) before you go on, so the check is clean again. Most calls leave the type argument to inference like this. Where there’s nothing to infer from, you write it, as you would for an empty new Map<number, Team>(). Suppose an AI assistant suggests a shorter request function with no guard:

Language: TypeScript
async function request<T>(path: string): Promise<T> {
  const response = await fetch(API + path);
  return response.json();
}

const teams = await request("/teams");

Nothing in the call says what T is, so the checker makes it unknown. Loop over teams, or use it as a list any other way, and the checker reports error TS18046, 'teams' is of type 'unknown'. Specify the type argument with await request<Team[]>("/teams"), and the check is clean.

Spot a Type Parameter Used Once

Does that clean check mean the call is right? Look at where T appears in the signature: once, in Promise<T>. No argument mentions it, so <Team[]> is your claim, and nothing checks it. It’s no safer than writing as Team[].

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.