Skip to content

Type inference doesn't discard 'undefined' possibility of an optional property inside an if(obj[name].optionalProperty) #19193

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
lmcarreiro opened this issue Oct 15, 2017 · 3 comments
Labels
Duplicate An existing issue was already created
Milestone

Comments

@lmcarreiro
Copy link

TypeScript Version: 2.6.0-dev.20171015

Code

interface A {
    arrayOfB?: B[];
}

interface B {
    prop: number;
}

var obj: { [name: string]: A } = {};

for (let name in obj) {
    if (obj[name].arrayOfB) { // make sure that obj[name].arrayOfB is not undefined
        for (let b in obj[name].arrayOfB) { // error in 'obj[name].arrayOfB': [ts] Object is possibly 'undefined'.

        }
    }

    // in this way it is ok, no errors
    let arrayOfB = obj[name].arrayOfB || [];
    for (let b in arrayOfB) {
        
    }
}

Expected behavior:
Infer that obj[name].arrayOfB is of type B[]

Actual behavior:
Considering obj[name].arrayOfB of type B[]|undefined

@mhegazy mhegazy added the Bug A bug in TypeScript label Oct 16, 2017
@mhegazy mhegazy added this to the TypeScript 2.7 milestone Oct 16, 2017
@fenying
Copy link

fenying commented Nov 11, 2017

Yes, I'm in trouble of this problem, that really make me sick....

I wish this could be solved ASAP. T_T

@lmcarreiro
Copy link
Author

You could use this pattern, I use it for string.match(/regex/) too:

    let arrayOfB = obj[name].arrayOfB || [];
    for (let b in arrayOfB) {
        
    }

    let matches = ("string".match(/regex/) || []);
    matches.forEach(/*...*/);

@mhegazy mhegazy modified the milestones: TypeScript 2.7, TypeScript 2.8 Jan 9, 2018
@mhegazy mhegazy modified the milestones: TypeScript 2.8, TypeScript 2.9 Mar 9, 2018
@mhegazy mhegazy modified the milestones: TypeScript 3.0, Future Jul 2, 2018
@sandersn sandersn removed their assignment Jan 7, 2020
@RyanCavanaugh RyanCavanaugh added Duplicate An existing issue was already created and removed Bug A bug in TypeScript labels Mar 4, 2024
@RyanCavanaugh
Copy link
Member

#56389

@RyanCavanaugh RyanCavanaugh closed this as not planned Won't fix, can't repro, duplicate, stale Mar 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants