Skip to content
Onsite

TupleToObject<T>

EasyP2Coding

Implement TupleToObject<T>: given a tuple of strings, numbers or symbols (typically from as const), build an object type whose keys and values are the tuple's elements.

Elements that cannot be property keys, such as arrays or objects, must be a type error.

Tests your type must pass

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
const tupleNumber = [1, 2, 3, 4] as const
const sym1 = Symbol(1)
const sym2 = Symbol(2)
const tupleSymbol = [sym1, sym2] as const

type cases = [
  Expect<Equal<TupleToObject<typeof tuple>, { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }>>,
  Expect<Equal<TupleToObject<typeof tupleNumber>, { 1: 1; 2: 2; 3: 3; 4: 4 }>>,
  Expect<Equal<TupleToObject<typeof tupleSymbol>, { [sym1]: typeof sym1; [sym2]: typeof sym2 }>>,
]

// @ts-expect-error arrays and objects cannot be keys
type error = TupleToObject<[[1, 2], {}]>

Hints

TypeScript
Run and Submit type-check your solution against the tests.