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 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<test1Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.