Home > Blockchain >  Object is possibly 'null'.ts(2531) - React Typescript
Object is possibly 'null'.ts(2531) - React Typescript

Time:07-09

I fetch API data by axios. Everything is working correct. I try to convert js to tsx. The code for fetching data is briefly as below:

let list = null;
...
list = response.data
...
console.log(list.list[2])  //here the problem, first "list" item is red underlined, telling that (Object is possibly 'null'.ts(2531) )

The actual result of list is as follows:

{
"city":{...}
"cod":"200"
"message":6.1851422
"cnt":10
"list":[...]
}

I need the array of list.list. The app is working correctly, but I want to get rid of this warning. I am new to typescript, should I define a type for list? Or is there any other way to handle this warning?

CodePudding user response:

I think you want to define an interface for list then passing the type when you initialize list. Then do a check to make sure that list exists.

type Codes = "200" | "400" | "500"

type City = {
  city: string;
  address: string;
  state: string;
}

interface ListResponse {
  "city": City;
  "cod": Codes
  "message": number;
  "cnt": number;
  "list":string[]
 }

let list: ListResponse | null = null
...
list = response.data
...
if(list){
    console.log(list.list[2])
}

CodePudding user response:

you can use a ? operator (more about this here)

So, your code would look like:

list?.list

This short-circuits the expression as undefined if it's a nullish object!

Also, you can just wrap your statement around an if block where you check if the list object is null or not!

NOTE: Additionally, you'd need to check the nature of your list.list variable before accessing it as an array!

Hope it helps!

  • Related