Sometimes, we want to use promise generic types with TypeScript.
In this article, we’ll look at how to use promise generic types with TypeScript.
How to use promise generic types with TypeScript?
To use promise generic types with TypeScript, we can use the Promise
generic type.
For instance, we write
const test = (arg: string): Promise<number> => {
return new Promise<number>((resolve, reject) => {
if (arg === "a") {
resolve(1);
} else {
reject("1");
}
});
};
to create the test
function which returns a promise.
To add the return type for the return value, we set the return type to Promise<number>
.
This means the promise return would resolve to a number.
Therefore, call resolve
with a number in the Promise
constructor callback would match the required return type.
Conclusion
To use promise generic types with TypeScript, we can use the Promise
generic type.