Ioan-Radu Tanasescu
Ioan-Radu Tanasescu

Reputation: 566

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?

Upvotes: 1

Views: 1862

Answers (1)

AntPraxis
AntPraxis

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

Related Questions