簡體   English   中英

Typescript 自定義類型守衛和數組操作

[英]Typescript custom type guards and array operations

抱歉,如果這是重復的,但我找不到我正在尋找的答案。

我開始嘗試使用 TypeScript 並且遇到了used-defined type guards 我想用它們來檢查一個數組是否為空,但我不知道如何正確地做到這一點。 這是我到目前為止所嘗試的。

function isEmpty<T>(array: Array<T>): array is [] {
  return array.length === 0;
}  

const arr = ['a', 'b', 'c'];
const result: string[] = [];

while (!isEmpty(arr)) {
  result.push(arr.pop())
  //          ^^^^^^^^^ Type error here because pop() returns string or undefined if the array is empty 
}

似乎 TypeScript 無法縮小 Array.prototype.pop() 的返回類型,因為它無法訪問其實現並且僅依賴於函數的簽名。

有沒有辦法使這項工作? 我對可讀性和類型安全最感興趣。 感謝您的時間

您需要使用類型斷言來告訴編譯器arr.pop()返回的項目類型是什么,因為arr可能為空並且結果變量的類型是字符串數組。 所以代碼將如下所示:

const isEmpty = <T>(array: T[]): array is [] => {
  return array.length === 0;
};

const arr = ["a", "b", "c"];
const result: string[] = [];

while (!isEmpty(arr)) {
  result.push(arr.pop() as string);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM