[英]Proper type for reducer's accumulator
如何描述以下代码的result
和acc
类型?
const arr = ['a', 'b', 'c'] as const;
const result = arr.reduce((acc, item, idx) => {
return {
...acc,
[item]: idx,
}
}, {});
取决于迭代acc
可以是:
首先我使用了这段代码:
type MyResult = Record<typeof arr[number], number>; //
type MyAcc = Partial<MyResult>;
但这是不正确的:
Types of property 'a' are incompatible.
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.(2322)
这是我的方法:
type ArrayItemType<A extends ReadonlyArray<any>> = A[number];
const arr = ['a', 'b', 'c'] as const;
type KeyIndexes = Record<ArrayItemType<typeof arr>, number>;
const result = arr.reduce((acc, item, idx) => {
return {
...acc,
[item]: idx,
}
}, {} as KeyIndexes);
KeyIndexes
是有效的:
{
a: number,
b: number,
c: number
}
...正如你在这个操场上看到的那样
我意识到从技术上讲,初始化器和累加器在归约的所有阶段都不是这种类型的反对意见,但是 TypeScript 确实没有办法弄清楚部分结果如何变成完整结果,所以你需要在反正有一点。
更新
如果您真的关心累加器的类型与结果的类型不同,则可以相应地调整类型,但您必须进行一些更难看的转换:
type ArrayItemType<A extends ReadonlyArray<any>> = A[number];
const arr = ['a', 'b', 'c'] as const;
type KeyIndexes = Record<ArrayItemType<typeof arr>, number>;
const result = arr.reduce((acc: Partial<KeyIndexes>, item, idx) => {
return {
...acc,
[item]: idx,
}
}, {}) as KeyIndexes;
(见操场)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.