scipper
scipper

Reputation: 3153

Compiler complains about possible undefined in nested objects

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

Upvotes: 0

Views: 630

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250036

Type guards (which is what you are using when you write if (objectVar[selector]) and expect the type to change based on the check) do not work with index access. This is documented in this and this issues. The reason for this is (as stated by @RyanCavanaugh in comments to the issue)

Declined due to performance reasons. Since it should almost always be possible to write const j = list[i] instead, this shouldn't be too burdensome.

As is stated above the recommendation is to use a local variable :

let objectVar: { [key: string]: number | undefined } = {a: 1};

const selector = "a";
const objectVar_selector = objectVar[selector]; 
if (objectVar_selector) {
    objectVar_selector.toFixed; // Object is possible undefined? o0
}

Upvotes: 1

Related Questions