1

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

1 Answer 1

2

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()
  ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, of course, appreciated ...
No problem at all :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.