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

Bug diagnosing error "Object is possibly 'undefined'" #31344

Closed
leopoldo8 opened this issue May 10, 2019 · 2 comments · Fixed by #44730
Closed

Bug diagnosing error "Object is possibly 'undefined'" #31344

leopoldo8 opened this issue May 10, 2019 · 2 comments · Fixed by #44730
Labels
Duplicate An existing issue was already created

Comments

@leopoldo8
Copy link

TypeScript Version: 3.4.5

Search Terms: Object is possibly 'undefined'

Code

function Sum(A?: number) {
    const AisUndefined: boolean = typeof A === "undefined";

    if (AisUndefined) {
        return 'is undefined';
    }

    const sum: number = A + 10; //Error here: "Object is possibly 'undefined'"
    return sum;
}

Expected behavior: As I assign the condition typeof A === "undefined" in the constant AisUndefined and make a if statement to return a string in case of A is definitely undefined, in the constant sum, there should be no problem making a sum of A with a number assuming that A is definitely not undefined as the code reach there, after the if statement.

Actual behavior: When I try to make a sum with A and a number, and probably any other operation that takes on that A is not undefined, typescript identifies this as an error, saying that Object is possibly 'undefined', basically ignoring the return inside the if statement.

Note: If I replace the constant AisUndefined by their own condition, like:

if (typeof A === "undefined") {
    return 'is undefined';
}

Therefrom, the error disappears.

Playground Link: https://www.typescriptlang.org/play//#src=function%20Sum(A%3F%3A%20number)%20%7B%0D%0A%20%20%20%20const%20AisUndefined%3A%20boolean%20%3D%20typeof%20A%20%3D%3D%3D%20%22undefined%22%3B%0D%0A%0D%0A%20%20%20%20if%20(AisUndefined)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20'is%20undefined'%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20const%20sum%3A%20number%20%3D%20A%20%2B%2010%3B%0D%0A%20%20%20%20return%20sum%3B%0D%0A%7D (You will have to check the strictNullChecks option to get this error)

Related Issues:

@jack-williams
Copy link
Collaborator

Duplicate of #12184

@fatcerberus
Copy link

Yeah, this is normal. Only direct type guards work; the compiler doesn't track the effect of assigning a type check result to another variable.

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

Successfully merging a pull request may close this issue.

4 participants