I have the following sample code: sample on typescriptlang.org (activate strictNullChecks)
1. let boolVar: number | undefined;
2.
3. if (boolVar) {
4. boolVar.toString; // all fine
5. }
6.
7. let objectVar: { [key: string]: number | undefined } = {a: 1};
8.
9. const selector = "a";
10. if (objectVar[selector]) {
11. objectVar[selector].toFixed; // Object is possible undefined? o0
12. }
Why does the compiler complains about line 11.: Object is possible undefined when I explicitly check for this object in line 10.?
objectVar[selector]could become undefined between theifcheck and theifblock. I found that if I savedobjectVar[selector]to a variable before theifstatement, and referenced that variable instead, the error went away.