Implement a type that extract prop value to the interface. The type takes the two arguments. The output should be an object with the prop values. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement ExtractToObject<T, U> which takes an object type and a key whose value is an object, then flattens that nested object's properties into the parent object while removing the original key.
Implement a type that extract prop value to the interface. The type takes the two arguments. The output should be an object with the prop values. Prop value is object.
For example
type Test = { id: '1', myProp: { foo: '2' }}
type Result = ExtractToObject<Test, 'myProp'> // expected to be { id: '1', foo: '2' }Change the following code to make the test cases pass (no type check errors).
type ExtractToObject<T, U extends keyof T> =
T[U] extends object
? { [K in keyof T | keyof T[U] as K extends U ? never : K]:
K extends keyof T[U] ? T[U][K] : K extends keyof T ? T[K] : never }
: neverA cleaner way to express this using Omit and intersection:
type ExtractToObject<T, U extends keyof T> = {
[K in keyof (Omit<T, U> & T[U])]: (Omit<T, U> & T[U])[K]
}How it works:
U extends keyof T constrains U to be a valid key of T, which causes ExtractToObject<test4, 'prop4'> to produce a ts-expect-error since 'prop4' is not a key of test4Omit<T, U> removes the specified key U from the object type, keeping all other properties& T[U] intersects the result with the value type at key U, effectively merging the nested object's properties into the parent{ [K in keyof (...)]: (...)[K] } flattens the intersection into a clean object type, so instead of Omit<T, U> & T[U] you get a single object with all properties listed{ id: '1', myProp: { foo: '2' } } with U = 'myProp', the result is { id: '1', foo: '2' }This challenge helps you understand object type manipulation using Omit, intersections, and mapped type flattening, and how to apply these concepts 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