Tuple to Object
Problem - On Github
The aim is to take an array type, and convert it to an object with the key/value pair of each element.
Out initial type given by the puzzle creator is
type TupleToObject<T extends readonly any[]> = any
Solution
For this challenge we need to look at a new bit of syntax for accessing values of a constant array - also known as a readonly tuple. This can be done by accessing the number
of the tuple type, which looks like T[number]
.
Other than this new syntax, there is not a lot different between this and the Readonly challenge. We want to:
- be an object -
{ ... }
- have its keys be from the tuple -
{ [Value in T[number]] ...}
- have the values from the tuple -
Value
This leaves us with:
type TupleToObject<T extends readonly any[]> = {
[Value in T[number]]: Value;
}
Fixing the key type
Our code above does in fact do what we want it to, but there is an issue with out keys. Typescript knows that an objects keys must be a string, number or symbol, but we have specified that we allow an any array.
To fix this lets pass in a stricter type.
type KeyType = string | number | symbol;
type TupleToObject<T extends readonly KeyType[]> = {
[Value in T[number]]: Value;
}
What to read more? Check out more posts below!