【发布时间】:2021-11-05 03:44:05
【问题描述】:
在以下示例中,我尝试将异步 const 函数分配为 Promises 到父对象的属性,因此可以在进一步的代码中延迟访问它,例如示例中的 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);
}
【问题讨论】:
标签: javascript angular typescript