Skip to content

Compiler complains object is possibly undefined after assigning a value #31060

Description

@yhvicey

TypeScript Version: 3.5.0-dev.20190420

Search Terms: Object is possibly 'undefined'

Code

interface SomeObject {
    prop: string
}

interface SomeComplexObject {
    prop: SomeObject
}

export class SomeClass {
    private prop: String;

    public constructor(someParam?: SomeObject, someOtherParam?: SomeComplexObject) {
        if (someParam === undefined && someOtherParam === undefined) {
            // <1>
            throw new Error("One of the params must be provided.");
        } else if (someOtherParam !== undefined) {
            // <2>
            someParam = someOtherParam.prop;
        }

        // If someParam === undefined, someOtherParam === undefined, it should goes to <1> and throw;
        // If someParam === undefined, it should goes to <2>, then someParam will be assigned with a non-undefined value, then goes to <3>;
        // If someParam !== undefined, it should goes to <3> directly and should not generate any error.
        // <3>
        this.prop = someParam.prop;
        //              ↑ Object is possibly 'undefined'.ts(2532)
    }
}

Expected behavior:

someParam won't be undefined and its props can be accessed

Actual behavior:

Compiler complains Object is possibly 'undefined'

Playground Link: Playground (Need to check strictNullCheck)

Related Issues: Not yet

Activity

  1. RyanCavanaugh commented on Apr 23, 2019

    @RyanCavanaugh
    Member

    Our flow control analysis isn't built to detect this kind of complementarity.

    The equivalent form

            if (someParam === undefined) {
                if (someOtherParam === undefined) throw new Error("One of the params must be provided.");
                someParam = someOtherParam.prop;
            }

    doesn't produce an error.

  2. yhvicey commented on Apr 23, 2019

    @yhvicey
    Author

    In fact, below snippet won't produce an error too:

    interface SomeObject {
        prop: string
    }
    
    interface SomeComplexObject {
        prop: SomeObject
    }
    
    export class SomeClass {
        private prop: String;
    
        public constructor(someParam?: SomeObject, someOtherParam?: SomeComplexObject) {
            if (someParam !== undefined) {
                // <1>
                // No op
            } else if (someOtherParam !== undefined) {
                // <2>
                someParam = someOtherParam.prop;
            } else {
                throw new Error("One of the params must be provided.");
            }
    
            // If someParam === undefined, someOtherParam === undefined, it should goes to <1> and throw;
            // If someParam === undefined, it should goes to <2>, then someParam will be assigned with a non-undefined value, then goes to <3>;
            // If someParam !== undefined, it should goes to <3> directly and should not generate any error.
            // <3>
            this.prop = someParam.prop;
            // More statements using someParam...
        }
    }

    Since I have ~5-6 statements using someParam and I prefer not to put them in an if-else block, I will use this one to workaround.

  3. dcsan commented on Aug 26, 2019

    @dcsan

    image

    why does the above check not prevent this error?

    ah workaround tx.btc_volume!

  4. yhvicey commented on Aug 27, 2019

    @yhvicey
    Author

    image

    why does the above check not prevent this error?

    ah workaround tx.btc_volume!

    Guess the compiler is complaining about tx.btc_volume might be undefined, not tx.

  5. dcsan commented on Aug 27, 2019

    @dcsan

    Yiwen Wang (@yhvicey) yes you were right. If i put the bang in the right place it shuts up tx.btc_volume!

  6. dcsan commented on Aug 27, 2019

    @dcsan

    I guess this will be a TS difference from the new JS feature with tx?.btc_volume? to fail out and not have to keep checking nulls. like coffeescript had many years ago...

  7. surabhi-sadhwani commented on Dec 30, 2019

    @surabhi-sadhwani

    In your tsconfig.js
    "strictNullChecks": false,
    "strict": false,

  8. hari1928 commented on Jan 7, 2020

    @hari1928

    look i have an angular code like this
    this.titleService.setTitle(this.SinglePost[0]['title']['rendered']);

    and its sowing me an error like

    ERROR in src/app/blog/blog.component.ts(93,40): error TS2532: Object is possibly 'undefined'.

    src/app/blog/blog.component.ts(93,56): error TS2339: Property '0' does not exist on type '[]'.

    so i got a solution of it

    var index =0;
          this.titleService.setTitle(this.SinglePost[index]['title']['rendered']);
    

    and now its working fine

  9. Tonterias commented on Jan 21, 2020

    @Tonterias

    I get an error saying: src/main/webapp/app/entities/local/newmenu-update.component.html(1,18137): Object is possibly 'null'. (when I deploy to heroku)

    But there is no line number 18137 in newmenu-update.component.html, so the question is: How can I find out where the problem is? I get like a 50+ of this errors in the same page.

  10. Yegorich555 commented on Mar 10, 2020

    @Yegorich555

    Also the issue exists when we have the following code:

    function someChecking(value?: {}) {
       const rules  = { key1: "v1", key2: "v2"}
       if (!value) {
           return false;
        }
    
       // allright this is nested function
        function isRuleFailed(ruleKey: string): any {
           // I get 'possible undefined' here - but it's wrong because function fired after checking value
           return value[ruleKey];
        }
    
        return isRuleFailed('required') || Object.keys(value).find(isRuleFailed)
        
    }
  11. suhaibmujahid commented on Mar 10, 2020

    @suhaibmujahid

    I have the same issue as Yegor (@Yegorich555).

    if (progress === undefined) return null;
    // Object is possibly 'undefined'.  TS2532
    if (progress.total === 0) return something;
  12. RyanCavanaugh commented on Mar 10, 2020

    @RyanCavanaugh
    Member

    This is not the thread to post every "I got an 'object is possibly undefined' error".

    Note that narrowing doesn't occur in unreachable code; if your code cannot be reached by any execution path, then you may see errors as a result.

    Please post self-contained bugs if you feel you've encountered an error you shouldn't have, or use Stack Overflow to help understand why you're seeing a particular error. Thanks!

  13. locked as off topic and limited conversation to collaborators on Mar 10, 2020
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

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions