Skip to content

Type of tuple element not inferred correctly when using const variable as index #10186

Closed

Description

TypeScript Version: 1.8.10

Code

enum Idx {
    Zero
}

const idxZero = 0;

type Tup = [string, number];

const t: Tup = ["5", 3];

const el1 = t[0];        // inferred type: string
const el2 = t[idxZero];  // inferred type: string | number, should be string
const el3 = t[Idx.Zero]; // inferred type: string | number, should be string

Expected behavior:

Type of el1, el2, el3 inferred by TypeScript should be string (same as type of first element of Tup).

Actual behavior:

Type of el1 is correctly inferred but type of el2 and el3 is not (it's inferred as string | number i.e. a union of all unique types of Tup type.

I understand that if an index can be an arbitrary value, that's the best TypeScript can do, but idxZero and Idx.Zero are constants and TypeScript should pick up on that.

This came up when trying to type a real-life code where for performance I send data from the server as array of arrays (vs. more verbose array of objects). I try to represent that as a tuple in TypeScript and have symbolic names for indexes into that tuple (as const idxFoo = 0 etc.), but using those symbolic names to index the tuple makes the result incorrectly typed.

Activity

  1. mhegazy commented on Apr 27, 2017

    @mhegazy
    Contributor

    This should be working as intended in latest.

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

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions