Skip to content

Suggestion: Access to element types of a tuple in generics #3420

Closed

Description

ES6 introduces an interesting use of iterable in Promise.all(), which takes Iterable<any | Promise<any>> and returns a Promise of Array<any>, where the elements of the result array follow the sequence of the iterable.

While TypeScript is not able to determine the type of each element of the result array when the input is an iterable, it should be able to do so when the input is an array or tuple, where the type of each element is known at input. However, there is no such language feature at the moment. I think that will be possible when access to element types of a tuple in generics is supported.

Therefore, I propose that a tuple generics constraint and an element type operator be added.

For example, with tuple() being the tuple generics constraint and * being the element type operator:

// Definition
function all<T extends tuple()>(values: Array<T* | Promise<T*>>): Promise<T>;

// Sample call
Promise.all<[string, number, boolean]>(["string", Promise.resolve(1), false])
.then(result => {
    let r1 = result[0].substr(1); // string
    let r2 = result[1] / 10; // number
    let r3 = !result[2]; // boolean
});

(Since T is a tuple, Array<T*> is equivalent to T.)

If the tuple generics constraint and the element type operator are added, Promise.all may have 2 overloads, one takes an iterable and another takes a tuple, with the latter one offers type information for each element of the result array.

Activity

  1. changed the title [-]Access to element types of a tuple in generics[/-] [+]Suggestion: Access to element types of a tuple in generics[/+] on Jun 9, 2015
  2. danquirk commented on Jul 9, 2015

    @danquirk
    Member

    May be that some extension of typeof is the right way to approach this if we were to go down this path.

  3. mhegazy commented on Dec 10, 2015

    @mhegazy
    Contributor

    The original proposal should be handled by #5453. The promise.all case has improved by adding oveloads in #5935. closing in favor of #5453.

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions