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

ChallengeSolution
type test1 = { id: '1'; myProp: { foo: '2' } }

type testExpect1 = {
  id: '1'
  foo: '2'
}

type test2 = {
  id: '1'
  prop1: { zoo: '2' }
  prop2: { foo: '4' }
}

type testExpect2 = {
  id: '1'
  prop1: { zoo: '2' }
  foo: '4'
}

type test3 = {
  prop1: { zoo: '2'; a: 2; b: 4; c: 7 }
  prop2: { foo: '4'; v: 2; d: 4; g: 7 }
  k: 289
}

type testExpect3 = {
  zoo: '2'
  a: 2
  b: 4
  c: 7
  prop2: { foo: '4'; v: 2; d: 4; g: 7 }
  k: 289
}

type test4 = { id: '1'; myProp: { foo: '2' } }

type testExpect4 = {
  id: '1'
  myProp: { foo: '2' }
}

type cases = [
  Expect<Equal<ExtractToObject<test1

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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