"Typescript asynchronous function can have either a return type of void or any other value

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.

Answer №1

the code snippet provided illustrates the importance of setting the correct return type in TypeScript functions.

instead of just returning NextFunction, it is recommended to set the return type as

Promise<NextFunction | IVerifiedCity>

export const verifyCityInDb = async (
    next: NextFunction,
    countryName: string,
    cityName: string,
    zipCodeValue: string
): Promise<NextFunction | IVerifiedCity> => {
    // function implementation goes here...
};

another approach could be defining the return type as

Promise<undefined| IVerifiedCity>

export const verifyCityInDb = async (
    next: NextFunction,
    countryName: string,
    cityName: string,
    zipCodeValue: string
): Promise<undefined| IVerifiedCity> => {
    // function implementation with error handling logic...
};

after calling the function, make sure to check if the verification was successful before proceeding further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Downloading EJS File instead of Displaying on Express.js Router

As I embark on the journey of developing a live video sharing/watching feature using Pure Node.js and without relying on any frameworks, an unexpected issue arose in the middle of the process. The problem occurred when Express started downloading an EJS fi ...

Maximizing the benefits of server side rendering

My curiosity about Server Side Rendering led me to discover a framework called nextjs during my Google searches. After giving it a try, I must say that I found it quite impressive. Now, I am determined to delve deeper into SSR by taking a dedicated course. ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Encountering a "Property does not exist on type" error when transitioning from JavaScript to TypeScript

Greetings, I recently made the transition from JS to TS for improved coding practices. However, TypeScript is throwing me these errors- the Validate function worked flawlessly in JavaScript. Property 'user' does not exist on type '{ isValid: ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

Is it possible to host both static content and views from a single directory?

Can I host static content and views from the same directory? I came across a partial solution below: //Implement Express for static content serving: app.use(express.static(__dirname + '/html')); //Specify folder named html as static path // ...

Shared cPanel causes Node Express Mongo app to enter sleep mode

I have encountered a strange issue while deploying a Node.js server with Express.js and MongoDB on NameCheap cPanel. It seems that I need to refresh the page 2 or 3 times to successfully retrieve data from the server, otherwise it returns a 404 error. Even ...

Leveraging Angular 8's ngIf directive in combination with the async pipe to dynamically display or hide HTML elements

I've been attempting to dynamically show and hide HTML elements based on the result of a service call. I have tried using *ngIf="messageService.getData() | async", but it doesn't seem to be working as expected. With the async, the "Failure Messag ...

Encountering an error while unit testing Angular components with MatDialog: "Error: <spyOn>: open has already been spied upon."

Once I create an HTML file with a button, I trigger a poll to appear after an onClick event. Then, when the "submit" button is clicked on the dialog window, it closes and I intend to execute subsequent methods. In my TypeScript file: openDialogWindow() { ...

Although MongoDB is successfully functioning on the local server.js, an error message is displayed when running it on

After successfully deploying meanapp, MongoDB is functioning properly on my local Node server.js. However, when I deploy to Heroku, I encounter an error. 2019-06-04T02:49:12.401001+00:00 heroku[web.1]: State changed from up to starting 2019-06-04T02: ...

The validation for "classes" in props is not found - Linting issue

Today I encountered an issue with the linting process. It has always functioned properly, but now it is flagging an error related to the props "classes" when using React Hooks. My components are structured like this: import { withStyles, WithStyles } from ...

unable to access environment file

Recently, I delved into the world of TypeScript and created a simple mailer application. However, I encountered an issue where TypeScript was unable to read a file. Placing it in the src folder did not result in it being copied to dist during build. When I ...

Break down the object into more manageable sections

How can I separate the properties of the object returned from the results? Every time I try, I just end up with undefined. Do you have any suggestions? app.get('/bets/:id', function(req, res){ var id = req.params.id; function(err, resu ...

Encountered compile failure" "Syntax error: Unexpected symbol :" when trying to transition to TypeScript within the current create-react-app setup

Currently, I am in the process of transitioning my create-react-app from JavaScript to TypeScript. To help with this migration, I followed the steps outlined on create-react-app.dev and successfully installed the necessary packages by running: npm install ...

bespoke server utilizing a combination of Next.js, Node.js, and Express

Recently, I've been working on setting up a Next JS project alongside a node server and express. Here are the steps I took to create the project: To start, I created a new Next JS app using the command below npx create-next-app@latest test-next-app ...

Unable to attach [(ngModel)] to Angular's HTML

I am currently facing an issue while attempting to create an edit form using Angular. I am encountering an error related to binding values with [(ngModel)]. ERROR TypeError: Cannot read property 'name' of undefined Below is the TypeScript cod ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Using the spread operator in Typescript/Javascript to dynamically add members to an object based on certain conditions

I was exploring a method for conditionally adding members to an object, which I found here Below is the code I came up with: const theobj = { field1: "hello", field2: 1, data: { datafield1: "world", datafield2: 2 }, ...

Tips for navigating to a different route during the ngOnInit lifecycle event

How can I automatically redirect users to a specific page when they paste a URL directly into the browser? I would like users to be directed to the /en/sell page when they enter this URL: http://localhost:3000/en/sell/confirmation Below is the code I am ...

What steps should I follow to establish a connection between a Sequelize ORM and an Express application with an ElephantSQL Post

This is the setup in my express config.json file: { "development": { "username": "elcaaklk", "password": "oliBfN1v8h7-JPE3_UN3LJeT3-pf10aJ", "database":"elcaaklk", &quo ...