Tuple to Object
Given an array, transform it into an object type and the key/value must be in the provided array.
Tuple is an array with fixed values, e.g. ['tesla', 'model 3', 'model X', 'model Y']
.
Example
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type obj = TupleToObject<typeof tuple>
/*
expected:
{
'tesla': 'tesla',
'model 3': 'model 3',
'model X': 'model X',
'model Y': 'model Y'
}
*/
Solution
type TupleToObject<T extends readonly PropertyKey[]> = {
[K in T[number]]: K
}
// Example usage:
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type Result = TupleToObject<typeof tuple>
// Test it:
const result: Result = {
'tesla': 'tesla',
'model 3': 'model 3',
'model X': 'model X',
'model Y': 'model Y'
}
T extends readonly PropertyKey[]
: This ensures that T is a readonly tuple of property keys[K in T[number]]
: This creates a new type by iterating over all elements of TK
: This is the current element of TK
: This is the value of the key in the resulting object
Playground
Summary
- Use
TupleToObject
when you want to transform an array into an object type - Use cases: Creating an object type from an array of fixed values