#3188Medium

Tuple to Nested Object

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.

Challenge Instructions: Tuple to Nested Object

Medium

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 type

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
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>>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

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:

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.

Share this challenge