In the last exercise, you gave the positions and the fields you sort players by one source each. One copy is still around. The registration form’s NewPlayer repeats the properties of Player, minus the id. Teams have the same kind of copy. The registration import creates a team before the API gives it an ID, and the update form sends only the fields a volunteer changed.
In this lesson, you’ll derive those types from Team with TypeScript’s utility types, so a change to Team reaches all of them. You’ll also learn where these utilities stop, which matters the first time you update a nested object. Start with the two types the forms need.
Derive the Create and Update Types
A type copied by hand drifts as soon as the original changes, so start from the values the two forms send. The registration import sends a new team without an id, because the API adds one. The update form sends only what changed:
const otters = {
name: "Mill Lane Otters",
ageGroup: "U10",
coach: {
name: "Daniel Okafor",
email: "[email protected]",
phone: "555-0134",
},
};
const moveUp = { ageGroup: "U12" };
Neither value is a Team: otters has no id, and moveUp has only ageGroup. You could copy Team twice and edit each copy, but you’d be back to types that drift.
A utility type is a generic type that comes with TypeScript. You pass it a type as its type argument, the way you filled in ApiResult<T>, and it gives back a reshaped type. In types.ts, give the ageGroup property of Team the AgeGroup type read off the age group list, and add two lines below the Team definition:
types.ts
export const AGE_GROUPS = ["U8", "U10", "U12"] as const;
export type AgeGroup = (typeof AGE_GROUPS)[number];
export type Team = {
id: number;
name: string;
ageGroup: AgeGroup;
coach: { name: string; email: string; phone: string };
};
export type NewTeam = Omit<Team, "id">;
export type TeamUpdate = Partial<NewTeam>;
Omit<Team, "id"> is Team without the keys you list: it removes id and keeps name, ageGroup, and coach.
Partial<NewTeam> makes each of those optional, so an update can carry one property or all three. Annotate the two values as otters: NewTeam and moveUp: TeamUpdate, and the type check passes. Give Team a new property, such as the team’s colors, and both types follow.
Partial changes every property without listing them because it’s a mapped type. Its declaration in TypeScript walks over keyof T and rewrites each property as optional. You’ll recognize that shape, { [K in keyof T]?: T[K] }, but you won’t need to write one in this course.
To see how Omit gets from Team to NewTeam, ask the mentor to walk you through it. This button opens a chat with the question filled in: