简体   繁体   中英

ts(2355) when attempting to return an array of documents NodeJS, Mongoose, Typescript

Am playing around with Typescript, Mongoose, NodeJS and Express, using the sample MongoDB data based on restaurants.

Am attempting to create simple CRUD operations, with the intent on returning All restaurants, then a specific restaurant and eventually filter/sort etc.

See the function below:

const fetchRestaurants = async (request: Request, response: Response): Promise<RestaurantInterface[]> => {
  try {
    const restaurants: RestaurantInterface[] = await RestaurantModel.find();
    response.status(200).json({
      restaurants
    });
  } catch (error) {
    throw error;
  }
}

If I remove this line Promise<RestaurantInteface[] (or switch strict: false ) I have no issues otherwise it alternates between.

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355) and if I attempt to return the response Type 'Response<any, Record<string, any>>' is missing the following properties from type 'RestaurantInterface[]': length, pop, push, concat, and 26 more.ts(2740)

Do I have basically loosen up the ts compiler or is there something I've misunderstood?

// in another file
export interface RestaurantInterface {
  name: string,
  borough: string,
  cuisine: string,
  restaurant_id: string
  address: Address,
  grades: Grades[],
};

Well it is expected, because the function actually returns void. When you write function name(): Promise<...> it means that you should return something. Whereas you are just calling the json method of the Express. So it is expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM