在下面的示例中,我嘗試將異步常量函式作為 Promise 分配給父物件的屬性,因此可以在進一步的代碼中延遲訪問它,例如示例中的 fn: async 函式 getItem()。
但是當將 const-s 分配給屬性 'subItems' 時,我收到錯誤:
型別 'ItemI' 缺少型別 'Promise' 中的以下屬性:然后,捕獲,最后,[Symbol.toStringTag]ts(2739)
你能解釋一下我缺少什么以及如何使它正確嗎?謝謝你。
// interface for each item object
interface ItemI {
id: number,
name: string,
subItems?: Promise<ItemI>[]
}
// item object 1
const item_A01: ItemI = {
id: 1,
name: 'item_A01'
}
// item object 2
const item_A02: ItemI = {
id: 2,
name: 'item_A02'
}
// async constant - Promise of each item object
async const async_item_A01 = (): ItemI => { return item_A01 };
async const async_item_A02 = (): ItemI => { return item_A02 };
// parent item with the Promissed item objects
async const parentItem: ItemI = {
id: 0,
name: 'parentItem',
// ERROR:
// Type 'ItemI' is missing the following properties
// from type 'Promise<ItemI>':
// then, catch, finally, [Symbol.toStringTag] ...
subItems: [async_item_A01(),
async_item_A02()
]
}
// function to work with an actual item
// from the Promissed / async constants
// by the provided index
async function getItem (itemIndex: number) {
const resolved_item: ItemI = await parentItem.subItems[itemIndex];
console.log('my resolved item is:', resolved_item.name);
}
uj5u.com熱心網友回復:
它是async不應該的功能const。此外,回傳型別應該是Promise<ItemI>:
const async_item_A01 = async (): Promise<ItemI> => { return item_A01 };
const async_item_A02 = async (): Promise<ItemI> => { return item_A02 };
另外,洗掉async這里:
const parentItem: ItemI = {
id: 0,
name: 'parentItem',
subItems: [
async_item_A01(),
async_item_A02()
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349605.html
標籤:javascript 有角的 打字稿
