Deriving Types With keyof and typeof

Every endpoint’s reply now comes from one ApiResult<T>. Other copies are still around, though. The fixture email script spells out the coach’s shape by hand, and the league table sorts by a column name that can be any string. Each copy can drift away from the original type.

In this lesson, you’ll derive types from the types and values you already have, with keyof, typeof, and indexed access, so each fact lives in one place. You’ll also learn to tell where a name stands for a type and where it stands for a value, which decides what typeof means. Start with the coach.

Read One Property’s Type

The fixture email script writes a line for each coach, and its function copies the coach’s shape out of Team:

Language: TypeScript
function coachLine(coach: {
  name: string;
  email: string;
  phone: string;
}): string {
  return `${coach.name} <${coach.email}>`;
}

If the coach in Team gains a field or loses one, this copy won’t follow. Instead, you can ask Team for the type of its coach property. Create coach.ts:

Language: TypeScript Filename: coach.ts
import type { Team } from "./types.ts";

type Coach = Team["coach"];

function coachLine(coach: Coach): string {
  return `${coach.name} <${coach.email}>`;
}

const lions: Team = {
  id: 1,
  name: "Riverside Lions",
  ageGroup: "U10",
  coach: {
    name: "Priya Nair",
    email: "[email protected]",
    phone: "555-0123",
  },
};
console.log(coachLine(lions.coach));

The check is clean, and Node.js prints the line:

Language: Shell
$ node coach.ts
Priya Nair <[email protected]>

Team["coach"] is an indexed access type. It looks like reading a property with brackets, but it reads from a type, and the result is the type of that property: { name: string; email: string; phone: string }.

Change the coach in types.ts, and Coach changes with it.

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.