Is it necessary to explicitly specify VOID when rejecting an empty Promise?

By default, promise rejection returns type void.

Promise.reject(reason?: any) => void

Imagine a scenario where we have a getUser function that retrieves a User object to be passed to a login function. We use a Promise that resolves when the user is found and rejects when no user is found or an error occurs.

// getUser returns an object or void
getUser(): Promise<object|void> {
  return new Promise((resolve, reject) => {
    // user is found
    resolve({ user: user });
    // user is not found or error
    reject();
  });
}

login(): void {
  this.getUser()
    .then((result: object) => {
      // get user here to send back
      this.res.status(200).json({
        user: result['user']
      });
    })
    .catch(() => {
      // don't need to receive data here
      this.res.status(500).json({
        error: 'No login'
      });
    });
}

Should the return type be explicitly set as VOID in the function signature?

getUser(): Promise<object|void>

Or is it sufficient to only specify the return type as object?

getUser(): Promise<object>

Answer №1

The parameter used in generic Promise<T> determines how the Promise will be resolved. In this scenario, using Promise<object> is appropriate (or even better, Promise<User> for a specific User type).

It is incorrect to use Promise<object | void> because a Promise does not resolve with void.

Typescript does not keep track of the type of value used to reject a Promise. This is because a Promise can be rejected not only by calling reject(), but also when an exception occurs and the types of exceptions are not monitored.

Another improvement that can be made to the code is to be more specific about the interface instead of using object:

interface User { user: string }; // Define the User interface

getUser(): Promise<User> {
  return new Promise((resolve, reject) => {
    // user is found
    resolve({ user: user });
    // user is not found or error
    reject();
  });
}

login(): void {
  this.getUser()
    .then((result: User) => {
      // Process user data to be sent back
      this.res.status(200).json({
        user: result['user']
      });
    })
    .catch(() => {
      // No need to handle data here
      this.res.status(500).json({
        error: 'Login failed'
      });
    });
}

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

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Issues with conditional types in TypeScript functionality not yielding desired results

Here is some TypeScript code that I am working with: type NumberOrNever<T> = T extends number ? T : never function f<T>(o: T) : NumberOrNever<T> { if (typeof o === "number") return o; throw "Not a number!" } ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

Ways to incorporate type into an object comprised of n element in Typescript

Is there a way to assign types to objects with different keys and values, but where "other" remains constant across all of them? How can this be achieved using TypeScript? { color: "red", size: "small", other: { price: 345 discount: 10 ...

Angular progress bar with dynamic behavior during asynchronous start and stop

Currently, I am facing an issue with the progress bar functionality while utilizing the ng-bootstrap module. The scenario involves a dropdown menu with multiple options, and my desired behavior includes: The ability to start/stop the progress bar indepen ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

Typescript absolute imports are not being recognized by Visual Studio Code

Encountered a similar unresolved query in another question thread: Absolute module path resolution in TypeScript files in Visual Studio Code. Facing the same issue with "typescript": "^4.5.5". Here is the content of my tsconfig.json: { ...

Obtaining the value from a defined inline script in Typescript

There is a generated value called "pageId" on the page, which is added inline in a script tag. <script> var pageId = @Model.Id </script> Now, I need to utilize this value in some Typescript (Angular App), but I am encountering an error statin ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...

Experiencing the error message "delete(...).then(...).error is not a function" while attempting to remove a file from Firebase storage using AngularFire and TypeScript

I'm trying to implement the code snippet from Firebase documentation to delete a file and then upload a new image in the same directory on Firebase Storage. However, I keep encountering an error message saying "delete(...).then(...).error is not a fun ...

Typescript: require generic types to include specific keys at all times

Is there a way to ensure that the function below only accepts a data object if it contains an id key, and then allows us to access the id from the data object? function someFuntion<T>(data : T){ const id = data['id'] //Error : Element imp ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Tips for triggering the update of index.view when the Save command is triggered within an active dialog

When I try to save in an open dialog using the Save command, the parent index.view does not update. However, everything works fine when using the SaveAndClose command. This was tested on the Product object at https://github.com/alex-kukhtin/A2v10.Web.Sampl ...