×

typescript · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.