0

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

2
  • Can TypeScript be multi-threaded? If so, there's the possibility that objectVar[selector] could become undefined between the if check and the if block. I found that if I saved objectVar[selector] to a variable before the if statement, and referenced that variable instead, the error went away. Commented Sep 21, 2018 at 14:12
  • @AlexPeters TypeScript transpiles to JavaScript and a crucial aspect of JS VMs is that they are single-threaded. Commented Sep 25, 2018 at 14:48

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice. good walkaround. thanks for pointing that out for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.