【发布时间】:2023-04-03 21:06:01
【问题描述】:
我有以下reduce 函数,我尝试的任何方法都没有消除错误:
interface ITask {
id: string;
was: string;
}
//sampleData:
const tasks = [
{id: "a", was: "Foo"},
{id: "b", was: "Foo"},
{id: "c", was: "Bad"}
];
const uniqueList = tasks.reduce<>((acc, current) => {
const x = acc.find((item: ITask) => item.was === current.was);
return !x ? acc.concat(current) : acc;
}, []);
这给了我:
Property 'find' does not exist on type 'never'.
Property 'was' does not exist on type 'never'.
Property 'concat' does not exist on type 'never'.
current 的值是 ITask 类型,accumulator 的类型是 ITask[]|[],这对我来说是绝对合乎逻辑的。因此,我尝试了:
const uniqueList = tasks.reduce<>((acc: ITask[] | [], current: ITask) => {
const x = acc.find((item: ITask) => item.was === current.was);
return !x ? acc.concat(current) : acc;
}, []);
这给出了:
Argument of type '(acc: ITask[] | [], current: ITask) => ITask[]' is not assignable to parameter of type '(previousValue: never, currentValue: never, currentIndex: number, array: never[]) => never'.
Type 'ITask[]' is not assignable to type 'never'.
Argument of type 'ITask' is not assignable to parameter of type 'ConcatArray<never>'.
Type 'ITask' is missing the following properties from type 'ConcatArray<never>': length, join, slice
编辑:
来自我尝试过的评论:
const uniqueList = tasks.reduce((acc, current: ITask) => {
const x = acc.find((item: ITask) => item.was === current.was);
return !x ? acc.concat(current) : acc;
}, [] as ITask[] | []);
这给了我:
Property 'find' does not exist on type 'never'.
Property 'concat' does not exist on type 'never'.
【问题讨论】:
-
你只需要输入累加器
...}, [] as ITask[]);或tasks.reduce<ITask[]>(...playground -
为什么是有条件的?它应该只是
useState<ITask[]>,除非您打算在其中存储其他东西? -
任何空数组仍然有一个类型。该类型表示只有该类型的元素才能添加到数组中,而不管它是否包含元素。这是一个 codesandox 显示 React 中的类型。
标签: javascript typescript reduce