Lesson 8 of 10
Looping over keys
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
A type built from another type's keys
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.
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- No type errors
- FormErrors has an optional string message for each field
- FormErrors rejects a field that isn't in the form
- Frozen keeps the type of each value
- Changing a value in Frozen causes a compile error