-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path00011-easy-tuple-to-object.ts
58 lines (45 loc) · 1.46 KB
/
00011-easy-tuple-to-object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
11 - Tuple to Object
-------
by sinoon (@sinoon) #easy
### Question
Give an array, transform into an object type and the key/value must in the given array.
For example
```ts
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'}
```
> View on GitHub: https://tsch.js.org/11
*/
/* _____________ Your Code Here _____________ */
type TupleToObject<T extends readonly any[]> = { [K in T[number]]: K }
/* _____________ 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-ignore @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>
/* _____________ Further Steps _____________ */
/*
> Share your solutions: https://tsch.js.org/11/answer
> View solutions: https://tsch.js.org/11/solutions
> More Challenges: https://tsch.js.org
*/