En el siguiente ejemplo, estoy tratando de asignar funciones asincrónicas constantes como Promesas a una propiedad de un objeto principal, por lo que se puede acceder de forma perezosa en otro código, como fn: función asincrónica getItem() en el ejemplo.
Pero al asignar const-s a la propiedad 'subItems' recibo un error:
Al tipo 'ItemI' le faltan las siguientes propiedades del tipo 'Promise': luego, catch, finalmente, [Symbol.toStringTag]ts(2739)
¿Podría explicar lo que me estoy perdiendo y cómo corregirlo? Gracias.
// 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); }Es la función la que debe ser async , no la const . Además, el tipo de devolución debe ser Promise<ItemI> :
const async_item_A01 = async (): Promise<ItemI> => { return item_A01 }; const async_item_A02 = async (): Promise<ItemI> => { return item_A02 }; Además, elimine async aquí:
const parentItem: ItemI = { id: 0, name: 'parentItem', subItems: [ async_item_A01(), async_item_A02() ] }