Improved UX Around Promises
TypeScript 3.6 introduces some improvements for when Promise
s are mis-handled.
For example, it’s often very common to forget to .then()
or await
the contents of a Promise
before passing it to another function.TypeScript’s error messages are now specialized, and inform the user that perhaps they should consider using the await
keyword.
interface User {
name: string;
age: number;
location: string;
}
declare function getUserData(): Promise<User>;
declare function displayUser(user: User): void;
async function f() {
displayUser(getUserData());
// ~~~~~~~~~~~~~
// Argument of type 'Promise<User>' is not assignable to parameter of type 'User'.
// ...
// Did you forget to use 'await'?
}
It’s also common to try to access a method before await
-ing or .then()
-ing a Promise
.This is another example, among many others, where we’re able to do better.
async function getCuteAnimals() {
fetch("https://reddit.com/r/aww.json")
.json()
// ~~~~
// Property 'json' does not exist on type 'Promise<Response>'.
//
// Did you forget to use 'await'?
}
For more details, see the originating issue, as well as the pull requests that link back to it.