Given a tuple type ```T``` that only contains string type, and a type ```U```, build an object recursively. Learn tuple manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a TupleToNestedObject type that takes a tuple of string keys and a value type, then builds a deeply nested object type where each key wraps the next level.
Given a tuple type T that only contains string type, and a type U, build an object recursively.
type a = TupleToNestedObject<['a'], string> // {a: string}
type b = TupleToNestedObject<['a', 'b'], number> // {a: {b: number}}
type c = TupleToNestedObject<[], boolean> // boolean. if the tuple is empty, just return the U typeChange the following code to make the test cases pass (no type check errors).
type TupleToNestedObject<T extends string[], U> =
T extends [infer First extends string, ...infer Rest extends string[]]
? { [K in First]: TupleToNestedObject<Rest, U> }
: U;How it works:
T into its first element First (constrained to string) and the remaining elements Rest (constrained to string[]){ [K in First]: ... } using a mapped type with a single key, where the value is the recursive result of processing the rest of the tupleU directly, placing it at the innermost nesting levelTupleToNestedObject<['a', 'b'], number> first creates { a: TupleToNestedObject<['b'], number> }, which becomes { a: { b: number } }This challenge helps you understand recursive type construction and tuple-to-object transformation, 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