Transform tuple type into object type with same key and value in TypeScript
7 Apr 2021
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:
Arrays cannot do that as you see:
Iteration over tuple
Usually we iterate over objects and use Mapped Types:
With Indexed Access Types we can use number
type to get the type of tuple's elements:
extends readonly any[]
is required for callingT[number]
without errorsT[number]
gets the values from the tupleT
in
is for iteration over the valuesValue
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 ✅
Good job, don't forget to check the solution with tests on Playground
typescript