Skip to content

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

Closed
@yhvicey

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

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