Closed as not planned
Description
Search Terms
awaitable
Suggestion
Add an awaitable type for values that will be awaited.
type Awaitable<T> = T | PromiseLike<T>;
This is based on my question and a comment on StackOverflow
Use Cases
Two use cases come in mind immediately:
- A function accepts a callback that may either return a value synchronously, or may return a promise value. This will then probably be awaited.
- This is more of a specific version of 1, but this would be the return type of
Promise.then()
/Promise.catch
/Promise.finally
callbacks.
Also, this type could replace all 1334 occurrences that come up when running git grep '| Promise'
in the current TypeScript code base.
Examples
Callback example:
async function logAnswer(getAnswer: () => Awaitable<number>): Promise<void> {
const answer = await getAnswer();
console.log(answer);
}
logAnswer(() => 42);
logAnswer(() => Promise.resolve(42));
Promise example:
Promise.resolve('Hello, world!').then(
// This type annotation is silly. This is really just to show promise callbacks should accept `Awaitable<T>`.
(hello): Awaitable<string> => {
console.log(hello);
return hello;
},
);
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.