Home > front end >  How to assign async const to object's property in typescript / javascript
How to assign async const to object's property in typescript / javascript

Time:11-05

In the following example I am trying to assign async const functions as Promises to a property of a parent object, so it could be lazily accessed in further code, such as the fn: async function getItem() in the example.

But when assigning the const-s to the property 'subItems' I am getting error:

Type 'ItemI' is missing the following properties from type 'Promise': then, catch, finally, [Symbol.toStringTag]ts(2739)

Would you please explain what I am missing and how to make it right? Thank you.

                // 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);
}

CodePudding user response:

It is the function that should be async not the const. Also, the return type should be Promise<ItemI>:

const async_item_A01 = async (): Promise<ItemI> => { return item_A01 };
const async_item_A02 = async (): Promise<ItemI> => { return item_A02 };

Also, remove async here:

const parentItem: ItemI = {
  id: 0,
  name: 'parentItem',
  subItems: [
    async_item_A01(),
    async_item_A02()
  ]
}
  • Related