Skip to content

Lookup index in tuple #6226

Closed
Closed

Description

const x: [number, string] = [1, 'foo'];
const y = x[1]
y

TypeScript knows y is a string. However, if I ask for x[2], TypeScript tells me it is string | number. Why is this? I expected it not to compile.

Activity

  1. saschanaz commented on Dec 23, 2015

    @saschanaz
    Contributor

    It seems it needs more discussion. See also #5203.

  2. DanielRosenwasser commented on Dec 23, 2015

    @DanielRosenwasser
    Member

    This is because a tuple of length n is an anonymous type that has properties 0, ... n - 1, and which effectively extends an array of the union of all element types. Since it's a subtype of Array, it gets an index signature, whose output type is the union of all element types.

  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

    DuplicateAn existing issue was already createdQuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions