我即将解决这个问题,但找不到解决最后TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol
个编译器错误的方法.
所以,这是一个实用函数rowsToObjects()
,相当多的人可能在他们的项目中定义了一两次,它在概念上有点类似于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,
)
这会产生以下结果:
[
{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'},
]
实际的实现显然是微不足道的,但输入它会让我感到很困难:
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[];
当前代码对我来说似乎是合乎逻辑的,但编译器抱怨as TcolTuple[i]
部分:
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
我是不是漏掉了什么明显的东西?输入接近令人满意,但如果没有这as TcolTuple[i]
,它就无法识别哪个值属于哪个键,而只是将它们全部合并.