#11Easy

Tuple to Object

Transform TypeScript tuples into object types with this easy-level challenge. Learn about const assertions, mapped types, and literal types on TypeScriptPro.

Transform arrays into powerful object types with the Tuple to Object challenge! 🔄

In this easy-level challenge, you'll learn how to convert a tuple (read-only array) into an object type where each array element becomes both a key and its value. This pattern is incredibly useful when working with constant arrays that define allowed values, creating type-safe enums from arrays, or building lookup tables.

You'll explore const assertions, indexed access types, and how TypeScript's type system can transform data structures at the type level. This challenge bridges the gap between runtime values and compile-time types.

For this challenge, you will need to change the following code to make the tests pass (no type check errors).

Challenge Instructions: Tuple to Object

Easy

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

For example:

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
 
type result = TupleToObject<typeof tuple> // expected { 'tesla': 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
Loading...

Video Walkthrough

Detailed Explanation

To transform a tuple into an object, you need to understand how to iterate over tuple elements and use them as both keys and values.

The solution leverages TypeScript's ability to use tuple elements as keys:

type TupleToObject<T extends readonly PropertyKey[]> = {
  [Key in T[number]]: Key
}

Key concepts:

This creates an object where each tuple element appears as both the key and value, perfect for creating lookup tables or enums from constant arrays.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount

This challenge is originally from here.