镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

Description

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:

Activity

  1. jack-williams commented on May 10, 2019

    @jack-williams
    Collaborator

    Duplicate of #12184

  2. fatcerberus commented on May 12, 2019

    @fatcerberus

    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.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions