Skip to content

Strict mode - "Cannot invoke an object which is possibly 'undefined'" even if tested #22385

@xthezealot

Description

@xthezealot

TypeScript version:
2.7.2

Code (playground link, use strictNullChecks):

interface IWithOptionalMethod {
    om?(): any;
}

interface IFoobar {
    bar: { [index: string]: IWithOptionalMethod };
}

const foo: IFoobar = {
    bar: {},
};

// FAILS
Object.keys(foo.bar).forEach((key) => {
    if (foo.bar[key].om) {
        foo.bar[key].om(); // Cannot invoke an object which is possibly 'undefined'.
    }
});

// WORKS
Object.keys(foo.bar).forEach((key) => {
    let x = foo.bar[key].om;
    if (x) {
        x(); // OK
    }
});

Expected behavior:
No warning: foo.bar[key].omis tested and cannot be undefined (unless I missed something).

Actual behavior:
Warning: Cannot invoke an object which is possibly 'undefined'.

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