I'm beginning my path in Typescript and got a problem that i can solve. I'm trying to acess one index of one array inside the return of a API call. In the console the value is printed perfectly, but appears this message of error.
This is the interface i made :
interface Data {
list: [{
main: {
temp: number;
temp_min: number;
temp_max: number;
}
weather: [{
main: string;
description: string;
}]
clouds: [{
all: number;
}]
dt_txt: string;
}]
dt: number;
}
And that is the console.log I'm using:
data?.list[1].main.temp_min
This is the error that appears:
TS2532: Object is possibly 'undefined'. 109 | 110 | <> > 111 | {console.log(data?.list[1].main.temp_min)} | ^^^^^^^^^^^^^ 112 | {console.log(data?.list[3]?.main)} 113 | 114 | </>
And that is the return value from the console.log
:
Could you guys help me?
CodePudding user response:
Access the items using ?
data?.list?.[1]?.main.temp_min
Also, update the interface like this
interface Data {
list: {
main: {
temp: number;
temp_min: number;
temp_max: number;
}
weather: {
main: string;
description: string;
}[]
clouds: {
all: number;
}[]
dt_txt: string;
}[]
dt: number;
}
CodePudding user response:
Within an array, it is not guaranteed that you will have something in index 1.
Scenarios:
[undefined, undefined, <object>]
[<object>]
When possible, best practice is not to access arrays by index directly but use a methods like '.map' or '.forEach' to programatically go through each one.
CodePudding user response:
In TS you should make sure that the data at index i in an array is not undefined or null in order to access the properties of that index.
So you have 2 options to fix your issue:
- Add ? to check if your data is undefined or not:
console.log(data?.list[1]?.main?.temp_min);
- Add if condition:
if(data && !!data.list && data.list[1] && data.list[1].main) {
console.log(data.list[1].main.temp_min);
}