beraliv

Transform tuple type into object type with same key and value in TypeScript

Example of TupleToObject use
Example of TupleToObject use

Third challenge is TupleToObject

I would say it's rarely used. But what we want to achieve here is having identical keys and values 🙂🙂 for the result object

An array or a tuple?

What is the difference between arrays and tuples

TypeScript defines tuple as:

A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.

It means we can check length and will get the exact number:

Examples of tuples
Examples of tuples

Arrays cannot do that as you see:

Examples of arrays
Examples of arrays

Iteration over tuple

Usually we iterate over objects and use Mapped Types:

Example of Mapped Types
Example of Mapped Types

With Indexed Access Types we can use number type to get the type of tuple's elements:

Example of Mapped Types for tuples
Example of Mapped Types for tuples
  • extends readonly any[] is required for calling T[number] without errors
  • T[number] gets the values from the tuple T
  • in is for iteration over the values
  • Value is a tuple element which is used as a key and a value of Mapped Types

Let's rename it and we just completed another challenge ✅

Solution
Solution

Good job, don't forget to check the solution with tests on Playground

typescript

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter