Tuple to Nested Object

Challenge

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

Solution

Zur Lösung des Problems müssen wir über den Array laufen. Anschließend prüfen wir, ob H als Lookup Type genutzt werden kann. Falls ja, nutzen wir H als Eigenschaft und rufen rekursiv den Typen mit den restlichen Tupelelementen auf.

type TupleToNestedObject<T extends Array<unknown>, U> = T extends [
  infer H,
  ...infer T
]
  ? {
      // PropertyKey = number | string | symbol
      [Key in H as H extends PropertyKey ? H : never]: TupleToNestedObject<
        T,
        U
      >;
    }
  : U;

References

(Variadic Tuple Types)[https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html] - Intersection Types - Indexed Access Types - Mapped Types