【问题标题】:How to assign async const to object's property in typescript / javascript如何在打字稿/javascript中将异步常量分配给对象的属性
【发布时间】: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


    【解决方案1】:

    函数应该是async 而不是const。另外,返回类型应该是Promise&lt;ItemI&gt;:

    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()
      ]
    }
    

    【讨论】:

    • 嗯,当然,感谢...
    • 完全没问题:)
    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2021-06-29
    • 2014-01-16
    相关资源
    最近更新 更多