Skip to content

Tuple vs arrays casting mismatch #16391

Closed

Description

@Xample

TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)

Code
http://www.typescriptlang.org/play/#src=export%20interface%20Vector%20%7B%0A%20%20%20%20x%3Anumber%3B%0A%20%20%20%20y%3Anumber%3B%0A%7D%0A%0Atype%20Point%20%3D%20%5Bnumber%2C%20number%5D%3B%0A%0Aconst%20Vectors%3A%20Vector%5B%5D%20%3D%20%5B%5D%3B%0Aconst%20points%3AArray%3CPoint%3E%20%3D%20Vectors.map((Vector)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20return%20%5BVector.x%2C%20Vector.y%5D%3B%0A%7D)%3B%0A%0A%2F%2F%20This%20is%20working%0Aconst%20pointsOk%3AArray%3CPoint%3E%20%3D%20Vectors.map((Vector)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20return%20%3CPoint%3E%5BVector.x%2C%20Vector.y%5D%3B%0A%7D)%3B%0A%0A

export interface Vector {
    x:number;
    y:number;
}

type Point = [number, number];

const Vectors: Vector[] = [];
// Error in the affectation
const points:Array<Point> = Vectors.map((Vector) => {
        return [Vector.x, Vector.y];
});

// This is working
const pointsOk:Array<Point> = Vectors.map((Vector) => {
        return <Point>[Vector.x, Vector.y];
});

Expected behavior:
The compiler should understand I am returning a tuple and not an array of values
Actual behavior:
I get an error and need to cast the conversion to get the right behaviour

Activity

  1. w0rp commented on Jul 25, 2017

    @w0rp

    I have just encountered this same issue myself.

    I think the compiler should infer [1, 2] as [number, number], and allow [number, number] to be assigned to number[]. The same should hold for [1, 'a'] being inferred as [number, string] which should be allowed to be assigned to (number | string)[].

  2. RyanCavanaugh commented on Jul 25, 2017

    @RyanCavanaugh
    Member
  3. locked and limited conversation to collaborators on Jun 14, 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

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions