简体   繁体   中英

Typescript Object is possibly null even inside an if statement checking that the object is not null

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?

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) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM