TypeScriptLesson 11 of 16
readonly and utility types
Utility types build a new type from an existing one, so you never describe it twice. They are generics built into TypeScript.
Key points
- Readonly<T> and a readonly field forbid overwriting.
- Partial<T> makes every field optional, which suits updates.
- Pick<T, "a" | "b"> keeps only the listed fields; Omit<T, "id"> removes them.
- Record<K, V> is an object with keys K and values V.
- readonly string[] is an array without push or other mutating methods.
Example
interface Profile { readonly id: number; name: string; email: string;} type ProfileUpdate = Partial<Profile>; // every field becomes optionaltype PublicProfile = Pick<Profile, "id" | "name">; // only these two fieldstype NewProfile = Omit<Profile, "id">; // everything except idtype Scores = Record<string, number>; // keys are strings, values are numbers const patch: ProfileUpdate = { name: "Sam" };const card: PublicProfile = { id: 7, name: "Sam" };const draft: NewProfile = { name: "Kim", email: "kim@example.com" };const scores: Scores = { math: 5, art: 4 };// card.id = 8; // error: 'id' is read-only const week: readonly string[] = ["Mon", "Tue"];// week.push("Wed"); // error: push does not exist on readonly string[] console.log(`${patch.name} #${card.id}, ${draft.name}, math ${scores.math}, ${week.length} days`);One Profile produced four types, and no field is written twice. If Profile changes, the derived types follow automatically.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Make defaults read-only, patch a Partial and summary a Pick of two fields, add titles with Record and print "Default: light, 16px", "Mine: dark, 18px", "Night mode".
Output
What your program prints appears here.