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 cases = [
Expect<Equal<TupleToNestedObject<['a'], string>, { a: string }>>,
Expect<Equal<TupleToNestedObject<['a', 'b'], number>, { a: { b: number } }>>,
Expect<
Equal<
TupleToNestedObject<['a', 'b', 'c'], boolean>,
{ a: { b: { c: boolean } } }
>
>,
Expect<Equal<TupleToNestedObject<[], boolean>, boolean>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.