Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tuple allows access at any index #10965

Closed
OliverJAsh opened this issue Sep 17, 2016 · 6 comments
Closed

Tuple allows access at any index #10965

OliverJAsh opened this issue Sep 17, 2016 · 6 comments
Labels
Duplicate An existing issue was already created

Comments

@OliverJAsh
Copy link
Contributor

Version: 2 rc

Given:

    const cell: [ number, number ] = [ 0, 1 ];
    const y = cell[100]
    y

I expect cell[100] to error, but it doesn't. y has a type of number. This means it's very easy to me to have bugs whereby I'm asking for an index that doesn't exist (like asking for a property that doesn't exist on an object).

@aluanhaddad
Copy link
Contributor

This works because indexing is not verified. You can always index. What is weird is that cell[100] has type number, I would expect it have the same type as cell['100'], that is type any.

@yortus
Copy link
Contributor

yortus commented Sep 18, 2016

The current behaviour is to give 'unknown' elements the union of the tuple element types. It's clearer to see if the tuple has different element types:

const cell: [ string, number ] = [ '0', 1 ];
const u = cell[0];
u // u is string
const v = cell[1];
u // u is number
const y = cell[100]
y // y is string | number

But personally I don't think that's a logical deduction for the type system to make. All bets are off for indexes outside the tuple range. At runtime they are likely to return undefined.

@aluanhaddad
Copy link
Contributor

@yortus what I find odd is this

const cell: [ string, number ] = [ '0', 1 ];
const u = cell['0'];
u // u is string
const v = cell['1'];
u // u is number
const y = cell[100]
y // y is string | number
const y = cell['100']
y // y is any

@Igorbek
Copy link
Contributor

Igorbek commented Sep 19, 2016

See a proposal of fixing this #6229

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 19, 2016
@RyanCavanaugh
Copy link
Member

Duplicate #5203

@OliverJAsh
Copy link
Contributor Author

I noticed this as well, sort of related. Can anyone explain why?

    const xs = [1,2,3];
    const x5 = xs[5]; // type is number, expected number | undefined

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants