如何修复减速器类型定义? (TS2345)

时间:2019-03-31 18:21:13

标签: typescript reduce

我具有遍历数组并找到最可能的id对和不同字符计数器的功能。不正确的值返回为null,并且在映射函数之后,我过滤了所有这些null。

export const findLikelyPairsId = (testingId: string, testingIdIdx: number, allIds: string[]) => {
  const result = allIds
    .map((comparingId: string, comparingIdIdx: number) => {
      if (comparingIdIdx === testingIdIdx) return null;

      const difference: number = differedLetters(testingId, comparingId);
      const approvedDiffer: boolean = difference <= testingId.length - 1;
      return approvedDiffer ? [testingId, comparingId, difference] : null;
    })
    .filter(value => value !== null);

  return [...result];
};

仍然有打字稿在我的减速器功能上对我大吼大叫

Argument of type '(acc: any[], value: any[]) => any[]' is not assignable to parameter of type '(previousValue: any[], currentValue: (string | number)[] | null, currentIndex: number, array: ((string | number)[] | null)[]) => any[]'.

Types of parameters 'value' and 'currentValue' are incompatible.

Type '(string | number)[] | null' is not assignable to type 'any[]'.

Type 'null' is not assignable to type 'any[]'.
export const likelyListReducer = (acc: any[], value: any[]): any[] => {
  return acc[2] ? (acc[2] > value[2] ? [...value] : [...acc]) : [...value];
};

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

应用reducer时发生错误,因为数组的类型在.filter(value => value !== null);之后没有改变。 TypeScript仍然假定数组可能包含null,而reducer函数期望value: any[]作为第二个参数,因此它不接受null数组元素值。

There is a way to tell the compiler filter应该更改数组类型:您必须使用类型谓词作为过滤器回调,如该答案所述。您需要在某处定义此类型谓词功能

function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
    return value !== null && value !== undefined;
}

像这样在filter()中使用它:

.filter(notEmpty);

通过此更改,可以将findLikelyPairsId的返回类型推断为(string | number)[][],它是一个没有任何空值的数组的数组,希望可以使用。