Skip to content

Type guard do not narrow array element accessed inline #15492

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

Closed
caesarsol opened this issue May 1, 2017 · 2 comments
Closed

Type guard do not narrow array element accessed inline #15492

caesarsol opened this issue May 1, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@caesarsol
Copy link

TypeScript Version: 2.2.1

A type guard in a loop does not narrow an array element to its type inside the conditional.

On the opposite, the same works by accessing the array element using a variable in between.

This could be by design, but it's quite strange to me...

Code

declare function isNum(a: any): a is number
declare function acceptNum(c: number): void

let children: Array<string | number> = [3, 4, 5]

for (let i = 0; i < children.length; ++i) {
    if (isNum(children[i])) {
        acceptNum(children[i]); // error: Type string is not assignatable to type number 
    }
}

for (let i = 0; i < children.length; ++i) {
    const child = children[i];
    if (isNum(child)) {
        acceptNum(child); // no error
    }
}

TS play demo here

Expected behavior:
children[i] type narrowed to number inside the if body.

Actual behavior:
children[i] type is still string | number inside the if body.

@mhegazy
Copy link
Contributor

mhegazy commented May 1, 2017

Duplicate of #10530

@mhegazy mhegazy added the Duplicate An existing issue was already created label May 1, 2017
@caesarsol
Copy link
Author

Sorry about that, I searched with various keywords and nothing popped out. Very few of the phrasing in common!

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 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

3 participants