Is the return type of 'void' being overlooked in TypeScript - a solution to avoid unresolved promises?

When working in TypeScript 3.9.7, the compiler is not concerned with the following code:

const someFn: () => void = () => 123;

After stumbling upon this answer, it became apparent that this behavior is intentional. The rationale behind it makes sense (essentially, ignoring the return type when passing the function as an argument).

However, things take a turn when dealing with promises:

const someFn: () => void = () =>
  new Promise((resolve, reject) => reject(Error('onoez')));
someFn();

I am using ESLint's

@typescript-eslint/no-floating-promises
rule to catch unhandled promise rejections in my code. In the example above, since the linter believes someFn does not have a return value, it will not issue a warning.

Do I just have to accept this situation? If a function expects a () => void type callback and I provide it with an async function, the compiler won't flag any issues, leading to potential problems. Is there a way to prevent this?

Answer №1

When a function has a return type of void in TypeScript, it means that the return value cannot be used, regardless of what it is. However, this does not prevent the function from actually returning something. This behavior will remain unchanged.

The syntax () => void indicates that you do not need to know or use the return value because it is not important for your purpose. But in some cases, such as this one, the return value does matter.

To enforce that a function does not return any value at all, you can use a return type of undefined.

const someFn: () => undefined = () =>
  // Type 'Promise<unknown>' is not assignable to type 'undefined'.
  new Promise((resolve, reject) => reject(Error('oh no!')));

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

There is no valid injection token found for the parameter 'functions' in the class 'TodosComponent'

While working in my code, I decided to use 'firebase' instead of '@angular/fire'. However, I encountered an issue that displayed the following error message: No suitable injection token for parameter 'functions' of class &apos ...

"Enable email delivery in the background on a mobile app without relying on a server

I am currently in the process of developing a mobile app using Ionic. One feature I would like to incorporate is sending an email notification to admins whenever a post is reported within the app. However, I am facing challenges with implementing this succ ...

Is it possible to invoke Cucumber stepDefinitions from a separate project at the same directory level?

Currently, I have a project called integration_test that includes all test projects utilizing cucumberjs, typescript, and nodejs. Project1 contains the login implementation, and I would like to use this implementation in Scenarios from Project2 and Projec ...

Error Message in Terminal When Launching React Application Using Webpack

I am encountering several errors in the node terminal while attempting to launch my react-app [at-loader] ./node_modules/@types/webpack/index.d.ts:23:16 TS2665: The module name in augmentation is invalid. Module 'webpack/lib/dependencies/HarmonyE ...

I am facing an issue with my interface - the variable designed to store boolean values

Something unusual happened with Typescript - I assigned a string value to a boolean variable, but no error was generated. I purposely triggered an error in order to observe how Typescript would react, only to find that it did not produce the expected erro ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

Error message: The ofType method from Angular Redux was not found

Recently, I came across an old tutorial on Redux-Firebase-Angular Authentication. In the tutorial, there is a confusing function that caught my attention: The code snippet in question involves importing Actions from @ngrx/effects and other dependencies to ...

The compatibility issues between Karma and Jasmine testing configurations cause errors during the Ionic packaging process

I've recently added testing to my ionic app using karma + jasmine, along with a typescript pre-processor. Below are the dependencies I have, most of which were added specifically for testing: "devDependencies": { "@ionic/app-scripts": "1.0.0", ...

Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me? I am cur ...

Guide on deactivating the div in angular using ngClass based on a boolean value

displayData = [ { status: 'CLOSED', ack: false }, { status: 'ESCALATED', ack: false }, { status: 'ACK', ack: false }, { status: 'ACK', ack: true }, { status: 'NEW', ack ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

Tips for verifying the presence of a specific value within an array of union types

Given an array of a specific union type, I am trying to determine if a string from a larger set that includes the union type is present in the array during runtime: const validOptions: ("foo" | "bar")[] = ["foo", "bar"] type IArrType = typeof validOptions ...

The functionality of CSS transitions may be affected when dynamically adding a class

Creating a custom CSS for my main div: .main { height: 0%; position: absolute; width: 100%; z-index: 100; background: whitesmoke; bottom: 0; border-radius: 15px; padding: 20px; color: gray; left: 0; right: 0; transition: height 1s e ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

What steps can be taken to resolve an ESLing error in this situation?

Check out this code snippet: <template v-if="isTag(field, '')"> {{ getItemValue(item, field) ? getItemValue(item, field) : '&#8211'; }} </template> An issue has been identified with the above code: Er ...