How to fix/debug this particular (and preferably in general) TypeScript compilation error?

42 Views Asked by At

I have this TypeScript code (it's dirty, with comments because I decided to leave them to show various approaches I've tried):

function getPlacesToStopExchange(): {
  our: { i: number; val: number; }[];
  enemy: { i: number; val: number; }[];
  //[party in 'our' | 'enemy' ]: { i: number; val: number; }[];
} {
  return valuesByMoves.reduce((o, v, i) => {
    if (i === 0 || i % 2) {
      //  //we move
      const el: { i: number; val: number; } = { i, val: v, };
      o.enemy.push(el);
    } else {
    //  o.our.push({ i, val: v, } as { i: number; val: number; }));
    }
    return o;
  }, { enemy: [], our: [], });
}

On line 10: o.enemy.push(el); I'm getting this error:

error TS2345: Argument of type '{ i: number; val: number; }' is not assignable
to parameter of type 'never'.

134           o.enemy.push(el);

If I comment that line — no error is present, so I'm pretty sure it's there exactly, not on the type declaration of the function's return value or the reduce initial value.

Does anyone know how to solve this? I've seen other questions on SO which say virtually, that I have to specify the type in the place the error is occurring, but as one can see I've tried this in many ways.

Also I tried to look into the tsc code, but there is no call stack no nothing. So I don't know where to look.

So if someone provided a general advise on how to debug tsc errors, I'd be very grateful.

Thank you.

1

There are 1 best solutions below

0
d.k On

This has helped, namely specifying the reduce callback's initial value:

function getPlacesToStopExchange(): {
  our: { i: number; val: number; }[];
  enemy: { i: number; val: number; }[];
  //[party in 'our' | 'enemy' ]: { i: number; val: number; }[];
} {
  return valuesByMoves.reduce((o, v, i) => {
    if (i === 0 || i % 2) {
      //  //we move
      const el: { i: number; val: number; } = { i, val: v, };
      o.enemy.push(el);
    } else {
    //  o.our.push({ i, val: v, } as { i: number; val: number; }));
    }
    return o;
  }, { enemy: [], our: [], } as {
    our: { i: number; val: number; }[];
    enemy: { i: number; val: number; }[];
    //[party in 'our' | 'enemy' ]: { i: number; val: number; }[];
  });
}