Making object out of tuple

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

Arrays cannot do that as you see:

Examples of arrays

Iteration over tuple

Usually we iterate over objects and use 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

  • 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

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

typescripteasy

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️