Typescript promise generic type
You could define a custom Promise type that actually also cares about the type of the rejection. You can also just give it a single type and the reject type will be any
, like in a normal 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 is of type `number`
myPromise.catch((reason) => {}); //reason is of type `string`
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");
}
});
}