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).
// Video Solution: https://youtube.com/watch?v=CxPfcubGoGA
/* _____________ Your Code Here _____________ */
type AppendToObject<T, U, V> = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
type test1 = {
key: 'cat'
value: 'green'
}
type testExpect1 = {
key: 'cat'
value: 'green'
home: boolean
}
type test2 = {
key: 'dog' | undefined
value: 'white'
sun: true
}
type testExpect2 = {
key: 'dog' | undefined
value: 'white'
sun: true
home: 1
}
type test3 = {
key: 'cow'
value: 'yellow'
sun: false
}
type testExpect3 = {Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.