Almost there, but stuck on the final
TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol
compiler error.
Here's a nifty utility function called rowsToObjects()
that many developers have probably come up with at some point, somewhat resembling the concept of zip():
const objects = rowsToObjects(
['id', 'color' , 'shape' , 'size' , 'to' ] as const,
[ 1n, 'red' , 'circle' , 'big' , '0x0'] as const,
[ 2n, 'green' , 'square' , 'small' , '0x0'] as const,
[ 3n, 'blue' , 'triangle', 'small' , '0x0'] as const,
)
This code results in:
[
{id: 1n, color: 'red', shape: 'circle', size: 'big', to: '0x0'},
{id: 2n, color: 'green', shape: 'square', size: 'small', to: '0x0'},
{id: 3n, color: 'blue', shape: 'triangle', size: 'small', to: '0x0'},
]
The actual implementation is straightforward, but achieving correct typing is posing a challenge:
export function rowsToObjects<
Tobj extends { [i in keyof TcolTuple as TcolTuple[i]]: TvalTuple[i] },
TcolTuple extends readonly string[],
TvalTuple extends { [j in keyof TcolTuple]: unknown }
>(cols: TcolTuple, ...rows: TvalTuple[]): Tobj[];
While the current code seems logically sound, the issue arises with the as TcolTuple[i]
part:
TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol
Type TcolTuple[keyof TcolTuple] is not assignable to type string | number | symbol
Type
TcolTuple[string] | TcolTuple[number] | TcolTuple[symbol]
is not assignable to type string | number | symbol
Type TcolTuple[string] is not assignable to type string | number | symbol
Is there something obvious I'm overlooking here? The typing is almost satisfactory, but without as TcolTuple[i]
, it merges all values without recognizing their respective keys.