In this video, you made the league’s list of age groups the one place the age groups are written, and read the AgeGroup type off it, so the type follows every change to the list. Then you did the same for the match status object.
Key Points
- A hand-written union drifts from its list. When a volunteer adds
"U14"to the registration form’s list for next season but not totype AgeGroup = "U8" | "U10" | "U12",npm run checkrejects the Brookside Ospreys’ sign-up. To the type,"U14"isn’t an age group. Node still runs the file and prints both lines, because the check and the run are separate steps. as constkeeps each item’s literal type. With it,typeof AGE_GROUPSin a type position isreadonly ["U8", "U10", "U12", "U14"], a tuple of exactly the four strings that the checker treats as read-only.- Index the list’s type with
number. A list’s items sit at number indexes, so(typeof AGE_GROUPS)[number]asks for the type of an item at any index: the union of all four strings,"U10" | "U12" | "U14" | "U8"in the checker’s own order (a union’s order doesn’t matter). The parentheses saytypeofcomes first, then the index. TypeScript readstypeof AGE_GROUPS[number]the same way without them. - The type follows the list. With
type AgeGroup = (typeof AGE_GROUPS)[number], the Ospreys’"U14"passes, because the list says so, and Kestrel Park’s"U16"gets an error whose message spells out the four groups the type allows. - Keep
as const. Without it, the list’s type isstring[], so the index gives plainstring. Every string passes, and the check comes back clean for"U16". - An object works the same way, indexed by its keys.
typeof MatchStatusreads the object, the value, and gives its type.keyofon that type gives the object’s keys, the names"Scheduled","Played"and"Postponed". Indexing the object’s type with them,(typeof MatchStatus)[keyof typeof MatchStatus], gives its values,"scheduled","played"and"postponed". Aftertypeof,MatchStatusmeans the object. - The rule: write the list once,
as const, and read its type off it. For a list, index its type withnumber. For an object, index it with its own keys.
The Code
The age groups, with the type read off the list: