Implement a Generic Type that can append a new field to any object type. Master mapped types in TypeScript in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Generic Type that can append a new field to any object type. For that you take a key and a value and append it to the object type.
Implement a type that adds a new field to the interface. The type takes the three arguments. The output should be an object with the new field.
For example
type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }Change the following code to make the test cases pass (no type check errors).
type AppendToObject<T, U extends PropertyKey, V> = {
[Key in keyof T | U]: Key extends keyof T ? T[Key] : V
}How it works:
U to be a PropertyKey so it can be used as a key in the object.T and U ([Key in keyof T | U])T, we return the value of T[Key], otherwise it must be U so we return VThis challenge helps you understand TypeScript's advanced type system and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount