Reputation: 566
I'm trying to access a property inside of an object inside of an array based on a provided index, and even though I check for that object not to be null, typescript still complains that it could be null.
Also "selectedIndex" is actually a react state in my project.
const arrayOfObjects: {bar:{baz: string; qux: string;}}[] = [{bar: {baz: 'value', qux: 'value'}}];
let selectedIndex: number = 0; //can be changed
if (arrayOfObjects[selectedIndex].bar !== null) {
doSomethingWith(arrayOfObjects[selectedIndex].bar.baz);
// here there will be a typescript error saying that "bar" Object is possibly null
}
Any idea?
Upvotes: 1
Views: 1862
Reputation: 113
The error is due to the selectedIndex being a react state value which can change between statements
let var = arrayOfObjects[selectedIndex].bar;
if (var) {
doSomething(var.baz)
}
Upvotes: 2