#29650Medium

ExtractToObject

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.

Challenge Instructions: ExtractToObject

Medium

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).

Loading...

Detailed Explanation

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 }
    : never

A 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:

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.

Share this challenge

Learn the Concepts

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount