Skip to main content

Tuple to Object

introduction#

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;
const result: TupleToObject<typeof tuple>; // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
ts
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const;
const result: TupleToObject<typeof tuple>; // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}

start point#

ts
/* _____________ Your Code Here _____________ */
type TupleToObject<T extends readonly any[]> = any;
 
/* _____________ Test Cases _____________ */
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const;
 
type cases = [
Expect<
Equal<
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
TupleToObject<typeof tuple>,
{ tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }
>
>
];
Try
ts
/* _____________ Your Code Here _____________ */
type TupleToObject<T extends readonly any[]> = any;
 
/* _____________ Test Cases _____________ */
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const;
 
type cases = [
Expect<
Equal<
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
TupleToObject<typeof tuple>,
{ tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }
>
>
];
Try
Take the Challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type TupleToObject<T extends readonly any[]> = {
[k in T[number]]: k;
};
Try
ts
type TupleToObject<T extends readonly any[]> = {
[k in T[number]]: k;
};
Try
Checkout more Solutions