跳至主要內容

11. Tuple To Object

鸭梨小于 1 分钟

11. Tuple To Object

<题目描述>

::: playground#ts 11. Tuple To Object

@file index.ts

// ============= 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' }>>,
]

// @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>

// ============= Your Code Here =============
type TupleToObject<T> = any

:::

点击查看答案
type TupleToObject<T extends readonly (string | number | symbol)[]> = {
  [K in T[number]]: K
}