1

I have function that traverse array and find most likely pairs of id and differ characters counter. Incorrect values is returning as null and after mapping function i filter all of these nulls.

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];
};

Still typescript yelling at me on my reducer function, that

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];
};

What am I doing wrong?

anton zlydenko
  • 265
  • 1
  • 2
  • 6

1 Answers1

2

The error when applying reducer happens because the type of array does not change after .filter(value => value !== null);. TypeScript still assumes that array may contain null, and the reducer function expects value: any[] as second argument, so it does not accept null array element value.

There is a way to tell the compiler that filter should change array type: you have to use type predicate as filter callback, as explained in that answer. You need to define this type predicate function somewhere

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

and use it in the filter() like this:

.filter(notEmpty);

with this change, the return type of findLikelyPairsId is inferred as (string | number)[][], which is an array of arrays without any nulls, which hopefully will work.

artem
  • 46,476
  • 8
  • 74
  • 78