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).
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'}
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:
T extends readonly PropertyKey[]
ensures T is a tuple of valid object keys (string, number, or symbol)T[number]
accesses all elements in the tuple as a union type[Key in T[number]]
iterates over each element: Key
sets the value to be the same as the keyThis creates an object where each tuple element appears as both the key and value, perfect for creating lookup tables or enums from constant arrays.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount
This challenge is originally from here.