Skip to content

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'
}

Playground

Playground

Summary

References