Skip to content

Deeper inference of Promise types.Β #49390

Open
@jespertheend

Description

@jespertheend

Suggestion

πŸ” Search Terms

promise required infer label:Suggestion

βœ… Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

In TypeScript 4.1 the first argument of a promise's resolve function was made to be required rather than optional (see this blogpost). This is useful because it often catches legitimate bugs. The downside is that you always have to provide a type argument. It would be nice if TypeScript were better at inferring the types of Promises so that you don't always have to provide a type.
So for instance

new Promise(r => r(3));

Would automatically result in the type Promise<number>.

πŸ“ƒ Motivating Example

In TypeScript having to provide a type is not such a big deal. You can usually get away with something like:

await new Promise<number>(r => r(3));

But in Javascript with JSDoc, this same piece of code becomes:

/** @type {Promise<number>} */
const promise = new Promise(r => r(3);
await promise;

which is generally a lot less clean and less readable than the TypeScript equivalent.

πŸ’» Use Cases

I frequently find myself running across code like the following:

/** @type {(() => void)[]} */
const cbs = [];

async function test() {
    // Do something

    // wait until `cbs` have fired
    await new Promise(r => r());

    // Do something else
}

All I want to do here is wait in the middle of an async function until a certain event has happened and then move on. I won't even be using the return value of the promise most of the time.

But because the first argument is required, TypeScript will now complain that I'm calling r() without any arguments. (here's a playground example)

If the return type of the promise would be inferred, there' wouldn't be the need to create an extra variable and annotate the promise with the Promise<void> type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions