I am new to typescript and I'm trying to understand why I'm getting the following errors.
Type 'FindCursor<WithId>' is missing the following properties from type 'Topping': name, priceCents
and
Argument of type 'Promise' is not assignable to parameter of type 'void'
public async getToppingsData(ID: String): Promise<Topping> {
const data = await this.collection.find({ _id: ID });
if (data === null || data === undefined) {
throw new Error(`Could not find ${ID}`);
}
const toppingData: Topping = data;
return toToppingObject(toppingData);
}
public async getToppingsByIds(toppingIds: String[]): Promise<String[]> {
toppingIds.map((id) => {
const toppingArray = [];
toppingArray.push(this.getToppingsData(id));
const toppingNames = toppingArray.map((topping) => {
toppingNames.push(topping);
});
return toppingNames;
});
}
here is the toPizzaObject function
import { Document } from 'mongodb';
import { Pizza } from '../application/providers/pizzas/pizza.provider.types';
import { ObjectId } from 'bson';
interface PizzaDocument extends Document, Omit<Pizza, 'toppings' | 'id'> {
toppingIds: ObjectId[];
}
const toPizzaObject = (pizza: PizzaDocument): Pizza => {
return {
id: pizza._id.toHexString(),
name: pizza.name,
description: pizza.description,
toppings: pizza.toppingIds.map((toppingId) => toppingId.toHexString()),
imgSrc: pizza.imgSrc,
};
};
export { PizzaDocument, toPizzaObject };
CodePudding user response:
You messed up your map()
, your were returning nothing, hence the void
. Also you were not handle the Promise correctly, the return type wasn't matching.
Here is a suggestion:
public async getToppingsByIds(toppingIds: String[]): Promise<String[]> {
const toppingArray = [];
for (let id of toppingIds) {
const data = await this.getToppingsData(id);
toppingArray.push(data);
}
const toppingNames = toppingArray.map((topping) => {
return topping
});
return toppingNames
}
PS: await can't be used on map/forEach()
, that's why there is a traditional for-loop.