Typescript 为什么扩展键T不是有效的索引

Typescript 为什么扩展键T不是有效的索引,typescript,Typescript,我有这个: export function reduceByProp<T, Y extends keyof T>( array: T[], mapper: (a: T) => Y ): { [key: Y]: T } { return array.reduce( (previous: T, current: T) => ({ ...previous, [mapper(current)]: current }), {} ); } 导出函数r

我有这个:

export function reduceByProp<T, Y extends keyof T>(
  array: T[],
  mapper: (a: T) => Y
): { [key: Y]: T } {
  return array.reduce(
    (previous: T, current: T) => ({ ...previous, [mapper(current)]: current }),
    {}
  );
}
导出函数reduceByProp(
数组:T[],
映射器:(a:T)=>Y
):{[key:Y]:T}{
返回数组.reduce(
(先前的:T,当前的:T)=>({…先前的,[映射器(当前)]:当前的}),
{}
);
}

但是TypeScript对
[key:Y]
不满意,因为索引必须是
字符串或
数字。但是由于
Y
T
的一个键,因此默认情况下它也是一个字符串或数字,对吗?

我建议您将代码更改为如下所示:

function reduceByProp<T, K extends PropertyKey>(
  array: T[],
  mapper: (a: T) => K
) {
  return array.reduce(
    (previous, current) => ({ ...previous, [mapper(current)]: current }),
    {} as { [P in K]?: T }
  );
}
reduceByProp([{ foo: 1 }, { foo: 3 }, { foo: 5 }], v => v.foo % 2 === 0 ? "even" : "odd");
在我的版本中,它的返回类型是
{偶数?:{foo:number},奇数?:{foo:number}
。这些都是可选的,这很好,因为结果表明输出根本没有
甚至

好吧,希望这会有帮助;祝你好运


你能展示一个你试图用
reduceByProp
实现的示例调用吗?不确定这是不是在起作用,但是这个文档说
keyof
产生
string | number | symbol
,所以symbol可能把它搞乱了。我很容易告诉您将
{[key:Y]:T}
更改为
{[K in Y]:T}
,但我不确定您的其余代码,因为这些类型对我来说似乎不合适。我会将其更改为,除非您有理由,例如,您想将
Y
限制为
keyof T
,而不仅仅是任何键。@jcalz-现在可以了。:-)当然还有第二个。