Currently delving into typescript, I am navigating through the development of a typescript/express backend REST API using an MVC architecture.
I occasionally encounter challenges with creating helper functions that are able to return next(new AppError()) (identified as type void by typescript) or a valid value in case of successful execution.
Below is an example of a helper function used for verifying the existence of a country and city in my database:
import { IVerifiedCity } from "../interfaces/controllers/verifiedCityInterface";
import { NextFunction } from "express";
import AppError from "../utils/errors/appError";
import { HttpCodes } from "../utils/errors/httpStatusCode";
export const verifyCityInDb = async (
next: NextFunction,
countryName: string,
cityName: string,
zipCodeValue: string
): Promise<void | IVerifiedCity> => {
if (
zipCodeValue === undefined ||
zipCodeValue === "" ||
cityName === undefined ||
cityName === "" ||
countryName === undefined ||
countryName === ""
) {
// Return next with custom AppError if data is incomplete
return next(
new AppError(
"The information provided for postal code, city, and country did not result in a valid location in our database.",
HttpCodes.NOT_FOUND
)
);
} else {
// ...logic here to search in DB for existing items
return {
verifiedCountry: countryInDb,
verifiedZipCode: formattedZipCode,
verifiedCity: cityInDb,
};
}
};
In this scenario, the return type could be an error of type void or an object containing values of type IVerifiedCity defined elsewhere as shown below:
import { ICityFromDb } from "../models/city/cityFromDbInterface";
import { ICountryFromDb } from "../models/country/countryFromDbInterface";
export interface IVerifiedCity {
verifiedCountry: ICountryFromDb;
verifiedZipCode: string;
verifiedCity: ICityFromDb;
}
The issue arises with the return type declaration. The current declaration
Promise<void | IVerifiedCity>
generates an error stating 'void is only valid as a return type or generic type variable.'
If you have any insights on how to resolve this, your input would be greatly appreciated. Thank you! I have attempted various return type declarations such as
Promise<void | IVerifiedCity>
, but haven't come to a suitable resolution.