typescript · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A builds one property for every key.
A mapped type loops over keys, the way a for loop walks an array. { [K in keyof SignUp]: boolean } says: for every key K of SignUp, make a property with that name whose type is boolean. Add a key to SignUp and the new type follows.
A changes how each property behaves. Put readonly in front of the square brackets or ? after them to add it. A minus removes one: -? makes every property required, and -readonly makes them changeable again.
interface SignUp {
name: string;
email: string;
age: number;
}
type Touched = { [K in keyof SignUp]: boolean };
type Errors = { [K in keyof SignUp]?: string };
const touched: Touched = { name: true, email: true, age: false };
const errors: Errors = { email: "Email needs an @ sign." };
console.log(touched.age, errors.email, errors.name); A mapped type over keyof T copies each property's modifiers from T, unless you change them.
guess first
Label the traffic lights. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Light {
red: boolean;
amber: boolean;
green: boolean;
}
type Labels = { [K in keyof Light]: string };
const labels: Labels = { red: "Stop", green: "Go" };
console.log(labels.red);
your turn
Your turn. Map scores to passes.
Fill in the mapped type so Passed has a boolean for every subject in Scores.
fix it
The settings are complete, but the checker disagrees. Fix it.
- Read the error:
chosen.soundmight beundefined. Where did that come from? - A mapped type over
keyof Settingscopies the?modifier from each property ofSettings. - Remove it with a minus: write
-?after the square brackets on line 5.
nailed it
you can build types from other types now. :D
{ [K in keyof T]: X }makes one property per key.?andreadonlyare modifiers; a minus sign removes them.- Change the original type and the mapped type follows.
new words in your collection
- mapped type
- modifier
This lesson isn’t saved. A free account remembers every lesson you finish.