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

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

Closed
yhvicey opened this issue Apr 22, 2019 · 12 comments
Closed

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

yhvicey opened this issue Apr 22, 2019 · 12 comments
Labels
Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds

Comments

@yhvicey
Copy link

yhvicey commented Apr 22, 2019

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

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds labels Apr 23, 2019
@RyanCavanaugh
Copy link
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.

@yhvicey
Copy link
Author

yhvicey commented Apr 23, 2019

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.

@dcsan
Copy link

dcsan commented Aug 26, 2019

image

why does the above check not prevent this error?

ah workaround tx.btc_volume!

@yhvicey
Copy link
Author

yhvicey commented Aug 27, 2019

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.

@dcsan
Copy link

dcsan commented Aug 27, 2019

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

@dcsan
Copy link

dcsan commented Aug 27, 2019

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...

@surabhi-sadhwani
Copy link

surabhi-sadhwani commented Dec 30, 2019

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

@hari1928
Copy link

hari1928 commented Jan 7, 2020

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

@Tonterias
Copy link

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.

@Yegorich555
Copy link

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)
    
}

@suhaibmujahid
Copy link

I have the same issue as @Yegorich555.

if (progress === undefined) return null;
// Object is possibly 'undefined'.  TS2532
if (progress.total === 0) return something;

@RyanCavanaugh
Copy link
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!

@microsoft microsoft locked as off-topic and limited conversation to collaborators Mar 10, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Suggestion An idea for TypeScript Too Complex An issue which adding support for may be too complex for the value it adds
Projects
None yet
Development

No branches or pull requests

9 participants