Typescript: Compiler complains object is possibly undefined after assigning a value

Created on 22 Apr 2019  Â·  12Comments  Â·  Source: microsoft/TypeScript

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

Suggestion Too Complex

All 12 comments

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.

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.

image

why does the above check not prevent this error?

ah workaround tx.btc_volume!

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.

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

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

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

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

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.

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)

}

I have the same issue as @Yegorich555.

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

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

remojansen picture remojansen  Â·  3Comments

MartynasZilinskas picture MartynasZilinskas  Â·  3Comments

weswigham picture weswigham  Â·  3Comments

wmaurer picture wmaurer  Â·  3Comments

dlaberge picture dlaberge  Â·  3Comments