// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type cases = [
Expect<Equal<TupleToObject<typeof tuple>, { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }>>,
]
// @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>
// ============= Your Code Here =============
type TupleToObject<T extends readonly string[]> = {
[key in T[number]]: key
}
// usage:
type tuple = typeof (['name', 'string'] as const)
type obj = TupleToObject<tuple>
/*
{
'name': 'name',
'string': 'string'
}
*/
此处用到了一个方式,即 Tuple 如何转化为 union type?
type tuple1 = [number, string];
type unionType = number | string;
// how ??
type unionType1 = tuple1[number];