Lesson 8 of 10

Looping over keys

Goal

A type built from another type's keys

01

Explanation

Partial and Readonly aren't magic hidden inside the compiler. Each one is a single line you can write yourself. A mapped type walks over the keys of another type and builds a property for each key: { [K in keyof T]: boolean }, for example, gives every field of T a boolean value.

You can also add modifiers to each property: ? makes it optional, readonly stops it from being changed, and -? and -readonly remove them. The value doesn't have to be T[K] either: you can put any type you like there.

A derived type follows its source, so if you add phone to the form, it automatically gets a slot for an error message. Keep in mind that readonly is only a compile-time check. The object itself can still be changed at runtime.

02

Your task

Define FormErrors<T> so every key in T has an optional string message, and define Frozen<T> with the same properties and types, all of them read-only.

Checks

5 checks
  1. No type errors
  2. FormErrors has an optional string message for each field
  3. FormErrors rejects a field that isn't in the form
  4. Frozen keeps the type of each value
  5. Changing a value in Frozen causes a compile error
03

Hints

0/3
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.