typescript · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Utility types are mapped types that come ready-made.
Some mapped types are so useful that TypeScript ships them built in. Each one is a : you give it a type in <> and get a new one back. makes every property optional, perfect for an update that changes only a few fields.
does the opposite and removes every ?. Readonly<Pet> adds readonly everywhere. Spread works on objects too: { ...pet, ...changes } copies the old object, then lays the changes on top.
interface Pet {
name: string;
age: number;
toy?: string;
}
function update(pet: Pet, changes: Partial<Pet>): Pet {
return { ...pet, ...changes };
}
const rex: Pet = { name: "Rex", age: 4 };
const older = update(rex, { age: 5 });
const full: Required<Pet> = { ...older, toy: "ball" };
console.log(older, full.toy); When two spread objects share a key, the one written last wins.
guess first
Move a locked point. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Point {
x: number;
y: number;
}
const start: Readonly<Point> = { x: 0, y: 0 };
start.x = 5;
console.log(start.x);
your turn
Your turn. Edit a profile.
Choose the utility type that lets changes hold only some fields, then change one field of the profile.
fix it
The retry count might be missing. Fix the type.
- Read the error:
ready.retriesmight beundefined, even thoughwithDefaultsalways fills it in. - The return type
Optionsstill has every?. After the defaults, every field is there. - Change the return type on line 5 to
Required<Options>, then run.
nailed it
you have a toolbox of ready-made types. :D
Partial<T>makes every property optional, great for updates.Required<T>removes every?;Readonly<T>locks every property.- Utility types are mapped types that TypeScript ships built in.
new words in your collection
- utility type
- Partial
- Required
This lesson isn’t saved. A free account remembers every lesson you finish.