Tuple to Object - TypeScript Challenge Explained

Monday, March 13, 2023

My solution to the Tuple to Object TypeScript Challenge as part of my journey to Understanding the TypeScript Challenges.

Given an array, transform it into an object type and the key/value must be in the provided array.

Solution

Loop over the values in the tuple (array) and assign the values to both the key and the value of the object:

1type TupleToObject<T extends readonly any[]> = {
2  [K in T[number]]: K
3}

Explanation

  • { } Create object type
  • T[number] iterate over the values in the array
  • K in T[number] to loop over them and assign them to the key
  • K Assign the key to the value

Other posts


Tagged with: