.shift() 是否有可能回傳未定義?
P粉461599845
P粉461599845 2024-02-03 19:55:25
0
1
313

我正在編寫一個 TypeScript 函數,我的 IDE 告訴我,.shift() 的結果可能是未定義的,這會導致更多類型警告...

這是程式碼:

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
}

現在我明白,當您無法確定數組中是否有任何元素時,此警告是有意義的,在這種情況下 .shift() 將返回未定義。但在這種情況下,我的 while 循環僅在 temp.length 為真時運行,在這種情況下我知道 temp.shift() 將返回一個值而不是未定義...我錯過了什麼嗎?

P粉461599845
P粉461599845

全部回覆(1)
P粉668804228

shift 被定義為 Array 的通用方法,並具有以下簽名:

Array<T>.shift(): T |未定義

#因此,無論您的程式碼是否針對 temp.length 斷言,當您呼叫 shift 時,您都必須期望傳回類型:

T |未定義

#您只需新增一個預設值:

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

對於 temp.pop() 也是如此。

這裡是ts-遊樂場

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!