I use async / await a lot in JavaScript. Now I’m gradually converting some parts of my code bases to TypeScript.
In some cases my functions accept a function that will be called and awaited. This means it may either return a promise, just a synchronous value. I have defined the Awaitable
type for this.
type Awaitable<T> = T | Promise<T>;
async function increment(getNumber: () => Awaitable<number>): Promise<number> {
const num = await getNumber();
return num + 1;
}
It can be called like this:
// logs 43
increment(() => 42).then(result => {console.log(result)})
// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})
This works. However, it is annoying having to specify Awaitable
for all of my projects that use async/await and TypeScript.
I can’t really believe such a type isn’t built in, but I couldn’t find one. Does TypeScript have a builtin awaitable type?
Awaitable
everywhere in your codebase? Either your function returnsT
orPromise<T>
, either way your function can handle it – Equilibranttype Awaitable<T> = T | Promise<T>
isn't that complicated that writing it in multiple projects would that big of a problem – Equilibrant() => 42
is invalid if you usePromise<T>
as the signature, but you can just callawait 42
in typescript. – SicklyAwaitable<T>
. Might be worth doing an issue on the TypeScript issue list and a pull request adding it tolib.es5.d.ts
. :-) – Ocelotawaited
operator in TS3.9 that did not make is into the final release? github.com/microsoft/TypeScript/pull/35998 It seems to exactly fill this gap – Rebuttal