interface ApiResponse{
data: Student[];
}
interface Student {
name: string;
}
Given an example I'm 100% sure I will get data but in case data is an empty array this will generate a runtime error.
const response = await fetch(...);
response.data[0].name
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
I want typescript to warn me about possible empty array scenario. I am aware I can write it response.data[0]?.name
but in case someone in team does not use ?
we will have no idea about potential undefined.
CodePudding user response:
I suppose this means data can be empty array, can have students and can have undefined. Which forces me to use ?
in that case which was my goal.
interface ApiResponse{
data: (Student|undefined)[];
}
CodePudding user response:
Your answer provides a way to handle an array with undefined
elements. But how does this handle an empty array scenario? And your answer once again forces you to add ?
like in your question to solve this.
interface ApiResponse {
data: (Student | undefined)[];
}
interface Student {
name: string;
}
let response: ApiResponse = { data: [] };
console.log(response.data[0].name) // this will throw the same error as in your question as empty array isn't checked
if (response.data.length)
console.log(response.data[0].name) // the if condition fails if array is empty
else
console.log("Handling the empty array here...")
if (response.data.length) {
if (response.data[0])
console.log(response.data[0].name) // the if condition automatically fails if element is undefined, which means there is no need to add the undefined type in your interface
else
console.log("Handling the array element that is undefined...")
}