IssueRaiser

11 - Tuple to Object

Given: ```ts type TupleToObject<T extends readonly any[]> = any ```` First of all we need to get rid of `any[]`. Input array is `readonly` and has only strings as values. So we can use `readonly string[]` type (or `ReadonlyArray<string>`). ```ts type TupleToObject<T extends readonly string[]> = any ```` Then we should transform array [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) (`['tesla', 'model 3', 'model X', 'model Y'] as const`) to object type. [Mapped types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) to the rescue. We can iterate every value in array within mapped type using `in` keyword. ```ts type TupleToObject<T extends readonly string[]> = { [P in <somehow get T values>]: P } ``` And to get the values we should use [indexed access](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) `Array[number]`. ```ts type TupleToObject<T extends readonly string[]> = { [P in T[number]]: P } ```

Posted by ehpc on Aug 18, 2021, 11:46 AM

Tags

Related issues

Raise real-world problems, find people facing the same issue, and discuss solutions.3,000 issues0 comments

github (Other)

11 - Tuple to Object

ehpcAug 18, 2021, 11:46 AM

Given: ```ts type TupleToObject<T extends readonly any[]> = any ```` First of all we need to get rid of `any[]`. Input array is `readonly` and has only strings as values. So we can use `readonly string[]` type (or `ReadonlyArray<string>`). ```ts type TupleToObject<T extends readonly string[]> = any ```` Then we should transform array [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) (`['tesla', 'model 3', 'model X', 'model Y'] as const`) to object type. [Mapped types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) to the rescue. We can iterate every value in array within mapped type using `in` keyword. ```ts type TupleToObject<T extends readonly string[]> = { [P in <somehow get T values>]: P } ``` And to get the values we should use [indexed access](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) `Array[number]`. ```ts type TupleToObject<T extends readonly string[]> = { [P in T[number]]: P } ```

Comments (0)

No comments yet. Start the discussion.

Comment on this issue