Lately, I have been utilizing async / await functions quite frequently in my JavaScript projects. As I make the transition to TypeScript, I am gradually converting some sections of my code bases.
In certain scenarios, my functions require a function as an input that will be called and awaited. This function may return either a promise or a synchronous value. To handle this, I have created a custom type called Awaitable
.
type Awaitable<T> = T | Promise<T>;
async function increment(getNumber: () => Awaitable<number>): Promise<number> {
const num = await getNumber();
return num + 1;
}
You can call this function like so:
// logs 43
increment(() => 42).then(result => {console.log(result)})
// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})
While this approach works, it becomes cumbersome to specify Awaitable
every time I work on projects involving async/await and TypeScript.
I find it hard to believe that TypeScript does not already have a built-in awaitable type. Could there be one that I am overlooking? Does TypeScript offer a native awaitable type?