我查看了其他帖子,但我似乎無法讓他們的解決方案發揮作用。我有這個聯合型別和這個使用object[]來自該聯合型別的函式,但是它拋出錯誤說不length存在,因為我的型別 User 和 Query 都不是物件陣列。
type Results = object[] | User | Query;
class Pagination implements IPagination
{
totalPages: any[];
readonly itemsPerPage = 5;
public async Paginate(items:Results, page: number):Promise<Page>
{
const pages = Math.ceil(items.length / this.itemsPerPage); //<- error here
const paginatedItems = Array.from({ length: pages }, (_, index) =>
{
const start = index * this.itemsPerPage;
return items.slice(start, start this.itemsPerPage); //<- And here because slice is also an array method.
});
this.totalPages = [...paginatedItems];
return { totalPages: this.totalPages, currentPageRows: this.totalPages[page], itemsPerPage: this.itemsPerPage };
}
}
uj5u.com熱心網友回復:
在執行任何特定于型別的操作之前,您可以執行檢查以確保物件的型別正確。
更一般地,您不應該在您實際需要非常特定型別并且具有依賴于傳遞的特定型別的代碼的地方使用型別聯合。
可以在方法的頂部使用類似以下的內容,并且可以防止使用無效型別,但更好的方法是確保您的方法簽名只接受它可以實際使用的型別。
if (!Array.isArray(items)) {
return;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524769.html
標籤:打字稿联合类型
