Generic Type for Promise in Typescript

I have a sample Promise function that is shown below. When successful, it returns a number, and when unsuccessful, it returns a string. The compiler is asking me to specify some kind of generic type for the promise. In this scenario, what type should I specify? Should I use Promise<number> or Promise<number | string>?

function test(arg: string): Promise {
    return new Promise((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}

Answer №1

The type specified in the Promise should align with the expected return data type of the function, while the error type is assumed to be any and not explicitly declared within the Promise definition.

For instance:

function example(input: string): Promise<number> {
    return new Promise<number>((resolve, reject) => {
        if (input === "x") {
            resolve(10);
        } else {
            reject("Error occurred");
        }
    });
}

Answer №2

If you want to create a specialized Promise type that pays attention to the type of rejection as well, you can define a custom Promise type. Alternatively, you can simply assign it one type and have the reject type default to any, similar to a standard promise.


type CustomPromise<T, F = any> = {
    catch<TResult = never>(
        onrejected?: ((reason: F) => TResult | PromiseLike<TResult>) | undefined | null
    ): Promise<T | TResult>;
} & Promise<T>;

function test(arg: string): CustomPromise<number, string> {
    return new Promise((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}

const myPromise = test("a");
myPromise.then((value) => {}); //value has type `number`
myPromise.catch((reason) => {}); //reason has type `string`

Answer №3

const sampleFunction = (argument: string) => {
   return new Promise((resolve: (result: number) => void, reject) => {
    if (argument === "a") {
        resolve(1);
    } else {
        reject("1");
    }
  });
}

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

24-hour flatpickr timepicker

Can anyone assist me in setting my hour format to 24 hours instead of AM/PM in Angular? I've been struggling with it for the past 2 days. Below are my TypeScript and HTML code snippets: TypeScript: flatpickrOptions: any = { locale: French, enable ...

How can I link an object to a variable using a select tag in Aurelia with Typescript?

After successfully populating a select tag with options from a static array of objects in JSON, each option set to the object id, I encountered a new challenge. tvs: any[] = [ { "id": 1, "ip": "11.11.11.111", "port": "8080", "name": "tv 1" }, ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Ensure proper type checking for reducer using Flow

Trying to incorporate Flow into a Redux codebase has been my current challenge. As someone new to Flow, I have some experience with TypeScript. My goal is to detect incorrect action types within the reducer function. type Action = | { type: 'samp ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

Tips for updating the 'value' attribute content in Playwright for Angular version 15

I am seeking guidance on how to access and modify the content of the value attribute in the provided code snippet. <table> <thead> <tr>...</tr> </thead> <tbody> <tr>...</tr> ...

The type `Map<string, enum>` cannot be assigned to `{ [key: string]: enum }`. The indexing signature is not present in the type `Map<string, enum>`

Suppose we have the following: export enum Relationship {} export interface Invitee {} export interface InviteesResponse { invitees: Invitee[]; relationships: { [key: string]: Relationship }; // mapping userIds to relationships } async functio ...

Currently in the process of executing 'yarn build' to complete the integration of the salesforce plugin, encountering a few error messages along the way

I've been referencing the Github repository at this link for my project. Following the instructions in the readme file, I proceeded with running a series of commands which resulted in some issues. The commands executed were: yarn install sfdx plugi ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: https://i.sstatic.net/UNtEP.png In the Header.css file, I have defined a class: .mainHe ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

Incorporating Angular, Angular UI, and Typescript while using the "controller as" approach

I'm having trouble with the combination in the topic, there must be a minor mistake somewhere that's causing this issue. Controller: class JobCtrl { job: Object; public $inject = ['$log', '$resource', &apos ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

What does it signify when it is stated that "it is not a descendant of the indexer"?

Currently, I am diving into Typescript with the help of this informative guide on indexer types. There is a specific piece of code that has me puzzled: interface NumberDictionary { [index: string]: number; length: number; // okay, length shoul ...

Using typescript with Ramda's filter and prop functions can lead to unexpected errors

I'm new to TypeScript and currently facing the challenge of converting JavaScript functions that use Ramda library into TypeScript functions. The lack of clear TypeScript usage in the Ramda documentation is making this task quite difficult for me. Sp ...

Utilizing the `map` function for converting a `forEach`

I'm currently in the process of refactoring my code to use the map function instead of forEach. However, I am facing an issue with implementing a null check for order.FunctionStatusList while using map. Specifically, I need guidance on how to handle t ...

What is the best way to implement a hook in server-side rendering with Next.js?

However, the hook cannot be utilized in a server-side rendered page For instance: export const getServerSideProps: GetServerSideProps = async (ctx:any) => { const { data } = useLocalStorage() return { props: { data : data} } } ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...