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