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

Type guards do not work on array access expressions #11483

Closed
OleksandrNechai opened this issue Oct 10, 2016 · 5 comments
Closed

Type guards do not work on array access expressions #11483

OleksandrNechai opened this issue Oct 10, 2016 · 5 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@OleksandrNechai
Copy link

TypeScript Version: 2.0.3

Code

let list = [1, '2'];
for (let i = 0; i < list.length; i++) {
    const j = i;
    if (typeof list[j] === 'string') {
        console.log(list[j].charAt(0)); // Property 'charAt' does not exist on type 'string | number'
    }
}

Expected behavior:
Successful compilation, since the type of list[j] is made clear with type guard

Actual behavior:
error TS2339: Property 'charAt' does not exist on type 'string | number'

@aluanhaddad
Copy link
Contributor

I'm not sure if this is intended to work, it would stand to reason since j is const. But in the meantime the following workaround will get the job done

for (let i of list) {
    if (typeof i === 'string') {
        console.log(i.charAt(0));
    }
}

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript In Discussion Not yet reached consensus labels Oct 10, 2016
@mhegazy
Copy link
Contributor

mhegazy commented Oct 10, 2016

This is a duplicate of #10530

@RyanCavanaugh
Copy link
Member

@mhegazy the sample doesn't compile under Nathan's PR

@mhegazy
Copy link
Contributor

mhegazy commented Oct 10, 2016

well.. it did in a previous iteration. the result was all array indexes were narrowed adding high perf and memory pressure. the current iteration of the PR, only narrows strings, this seems to be less expensive. we can discuss a better implementation.

@RyanCavanaugh RyanCavanaugh added Design Limitation Constraints of the existing architecture prevent this from being fixed and removed In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Oct 31, 2016
@RyanCavanaugh
Copy link
Member

Declined due to performance reasons. Since it should almost always be possible to write const j = list[i] instead, this shouldn't be too burdensome.

@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
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

4 participants