During the development of my API in typescript, I encountered a situation where some controller actions can be synchronous while others cannot. To address this issue, I decided to specify a response type as follows:
type ActionResult =IHttpActionResult | Promise<IHttpActionResult>;
As I proceed with building these actions, when they shift towards being promise-based, I simply add the 'async' keyword and move on.
However, I faced an obstacle when typescript raised an error stating that "the return type of an async function or method must be the global Promise type."
I wondered why an async function couldn't return a union of T | Promise<T>
?
For instance:
type StringPromise = Promise<string>;
// The following two functions work as expected
async function getHello(): Promise<string> {
return 'hello';
}
async function getGoodbye(): StringPromise {
return 'goodbye';
}
type StringyThingy = string | Promise<string>;
// These next two functions work as intended
function getHoorah(): StringyThingy {
return 'hoorah!';
}
function getWahoo(): StringyThingy {
return new Promise(resolve => resolve('wahoo'));
}
// However, this function triggers the error:
// "the return type of an async function or method must be the global Promise type."
async function getSadface(): StringyThingy {
return ':(';
}
Below are some sample outputs for the provided code:
getHello().then(console.log);
getGoodbye().then(console.log);
console.log(getHoorah());
// It is likely that the library I am using employs typeguards for this purpose
const wahoo = getWahoo();
if (typeof(wahoo) === 'string') {
console.log(wahoo);
} else {
wahoo.then(console.log);
}