Skip to content

Incorrect typing when flip-flopping an array of tuples #10094

Closed

Description

TypeScript Version: nightly (2.0.0-dev.201xxxxx)

Playground

Code

const x: [string,number][] = [
    ['one', 1],
    ['two', 2],
    ['three', 3]
];

// Type of y should be [number,string][]
// Instead, it is (number|string)[][]
const y = x.map(([a,b]) => [b,a]);

Expected behavior:

This may be an expected feature of the language, and if so, please disregard.

I expected the type of y to be [number,string][]

Actual behavior:

Type of y is (number|string)[][]

Activity

  1. weswigham commented on Aug 2, 2016

    @weswigham
    Member

    As a workaround, you can cast your result:

    const y = x.map(([a,b]) => ([b,a] as [number, string]));

    Or, a personal favorite, write your own 'tuple constructor', which forces a tuple type to be inferred:

    function tuple<A, B>(a: A, b: B): [A, B] {
        return [a, b];
    }
    
    const y = x.map(([a,b]) => tuple(b, a));

    In any case, I think this is a duplicate of #6574, and discussion should probably continue there.

  2. dsifford commented on Aug 2, 2016

    @dsifford
    ContributorAuthor

    Whoops! Didn't see the other discussion. Sorry about that.

    And yep, I've been using casting. Totally not a giant issue for me, but just wanted to throw it out there.

    Love the tuple constructor! Clever!

    Thanks again 👍

  3. 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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions