Typescript promise generic type

2020-06-30 04:22发布

问题:

I've a sample Promise function like below. On success I return a number and on false I return string. The compiler is complaining to specify some kind of generic type to the promise. In this case what type I've to specify? Do I've to specify like Promise<number> or Promise<number | string>?

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

回答1:

The generic type of the Promise should correspond to the non-error return-type of the function. The error is implicitly of type any and is not specified in the Promise generic type.

So for example:

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