[Typescript Challenges] 3. Easy - Tuple to Object

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'}
/* _____________ Your Code Here _____________ */

type TupleToObject<T extends ReadonlyArray<string | number>> = {
  [Key in T[number]]: Key
}


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
const tupleNumber = [1, 2, 3, 4] as const
const tupleMix = [1, '2', 3, '4'] 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 tupleMix>, { 1: 1; '2': '2'; 3: 3; '4': '4' }>>,
]
  1. Have to use as const, if not, typeof tuple will be string[], with as const, then typeof tuple is ['tesla', 'model 3', 'model X', 'model Y']
  2. T[number] helps to loop over the array in sequence.
posted @ 2022-08-31 15:51  Zhentiw  阅读(29)  评论(0编辑  收藏  举报