Is it possible that .shift() returns undefined?
P粉461599845
P粉461599845 2024-02-03 19:55:25
0
1
354

I'm writing a TypeScript function and my IDE tells me that the result of .shift() may be undefined, which results in more type warnings...

This is the code:

function accumulateProofs(
  proofs: Proof[],
  requiredAmount: Number,
  strategy: 'middle' | 'ascending' | 'descending',
): Proof[] {
  const result:Proof[] = [];
  const temp = proofs.slice();
  let total = 0;
  switch (strategy) {
    case 'middle': {
      while (temp.length && total < desired) {
        const first = temp.shift();
        total += first.amount;
        result.push(first);
        if (total >= desired) {
          break;
        }
        const last = temp.pop();
        total += last;
        result.push(last);
      }
    }
  }
  return result
}

Now I understand that this warning makes sense when you can't be sure if there are any elements in the array, in which case .shift() will return undefined. But in this case my while loop only runs when temp.length is true, in which case I know temp.shift() will return a value instead of undefined... am I missing something?

P粉461599845
P粉461599845

reply all(1)
P粉668804228

shift is defined as a generic method of Array and has the following signature:

Array<T>.shift(): T |Undefined

So, regardless of whether your code asserts against temp.length, when you call shift you must expect the return type:

T |Undefined

You just need to add a default value:

const first = temp.shift() || { amount: 0 }

The same is true for temp.pop().

This is ts-playground

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template