I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.
What it a tuple?
tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
// Type 'number' is not assignable to type 'string'.
// Type 'string' is not assignable to type 'number'.
Now that we know what a tuple is, let's see what do we mean by Tuple to object.
const tuple = [1, '2', 3, '4'] as const
type result = TupleToObject<typeof tuple>
// expected { 1: 1; '2': '2'; 3: 3; '4': '4' }
So let's see that magic in action.
type TupleToObject<Type extends readonly any[]> = {
[Key in Type[number]]: Key
}
Time to break that sucker down.
TupleToObject<Type extends readonly any[]>
In a nutshell you can read this as, Type extends an array of any type that its length won't change, remember for tuples we do know it's length, that is why we define the tuple variable as const
so we cant modify it.
const tuple = [1, '2', 3, '4'] as const
and we pass its array type right here in the params TupleToObject<typeof tuple>
[Key in Type[number]]: Key
Here we extract the value of Key from the value at the position of the current index of the array (1, '2', 3, ...).
Note: More than its uses it helped me understand a lot of tuples, arrays and objects work, maybe it will help you too!
Thank you!
you can find me here My Twitter
Top comments (0)