Typescript: Negative tuple indexer should not be valid

Created on 27 Jun 2020  路  5Comments  路  Source: microsoft/TypeScript

TypeScript Version: 4.0.0-dev.20200625

Search Terms:
negative tuple indexer

Code

type t1 = [string, number][0]; // string
type t2 = [string, number][1]; // number
type t3 = [string, number][-1]; // (string | number)  ???

type u<t extends any[], u extends number> = t[u];

type u1 = u<[string, number], 0>; // string
type u2 = u<[string, number], 1>; // number
type u3 = u<[string, number], 2>; // undefined
type u4 = u<[string, number], 1.5>; // undefined
type u5 = u<[string, number], -0.5>; // (string | number)  ???

Expected behavior:
that type t3 = [string, number][-1]; emits a compile-time error "Tuple type '[string, number]' of length '2' has no element at index '-1'." and u5 is undefined.

Actual behavior:
t3 and u5 is a union of the types contained in the tuple.

Playground Link: playground link

In Discussion Suggestion

Most helpful comment

It's okay, let's chalk it up to it being Monday 馃槃

All 5 comments

Misread the code, so I prematurely marked this as a bug.

In expression positions, if we statically know the index, we will issue an error; otherwise, we'll let it slide.

declare let x: [string, number];

x[1.5]; // error
x[1.5 as number]; // no error

@ahejlsberg any thoughts here?

Maybe it doesn't matter' but this bug is for type indexes, not variable indexes (as in your example). type Apple = Banana[-1]. Also, we do statically know the the index in all of the examples provided, and they don't error like you say they should.

Yeah, I saw that, I mentioned expression positions. The questions are whether we can actually enforce the same checks in type-land and how often it comes up to be worth it if that causes problems.

Ah, I misread your comment. :) You were saying, "this is what we do with expressions" as a comparison for what we might do with types.

It's okay, let's chalk it up to it being Monday 馃槃

Was this page helpful?
0 / 5 - 0 ratings