Lesson 4 of 10
Deriving types
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
One type that all the others come from
Explanation
You have a single User type and need other shapes from it: a partial update, a short preview card, and a new user who doesn't have an id yet. Copying these shapes by hand works for a day. Then User changes, the copies stay as they were, and not a single error points you to them.
Utility types derive the new shape instead of copying it: Partial<T> makes every field optional, Pick<T, "a" | "b"> keeps only the fields you name, Omit<T, "a"> keeps every field except the ones you name, and Record<K, V> builds an object whose keys are K and whose values are V.
A derived type always follows its source. Change the type of id in User and every derived type changes with it, and any code that no longer fits shows an error right away.
Your task
Derive all four types from User: UserPatch with every field optional, UserPreview with only id and name, NewUser with every field except id, and RoleCounts with a count for each value of User["role"].
Checks
5 checks- No type errors
- UserPatch accepts any single field with its correct type
- UserPreview has only id and name
- NewUser has every field except id
- RoleCounts has a count for every role, with none missing