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?
Awaitableeverywhere in your codebase? Either your function returnsTorPromise<T>, either way your function can handle it - Arontype Awaitable<T> = T | Promise<T>isn't that complicated that writing it in multiple projects would that big of a problem - Aron() => 42is invalid if you usePromise<T>as the signature, but you can just callawait 42in typescript. - Silvermind