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粉6688042282024-02-04 09:33:31
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