interface ApiResponse{
data: Student[];
}
interface Student {
name: string;
}
舉個例子,我 100% 肯定我會得到資料,但如果資料是一個空陣列,這將產生一個運行時錯誤。
const response = await fetch(...);
response.data[0].name
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
我想要打字稿警告我可能的空陣列情況。我知道我可以寫它,response.data[0]?.name但如果團隊中有人不使用,?我們將不知道潛在的未定義。
uj5u.com熱心網友回復:
我想這意味著資料可以是空陣列,可以有學生,也可以有未定義。這迫使我?在那種情況下使用這是我的目標。
interface ApiResponse{
data: (Student|undefined)[];
}
uj5u.com熱心網友回復:
您的答案提供了一種處理包含undefined元素的陣列的方法。但這如何處理空陣列場景?您的回答再次迫使您?在問題中添加類似內容以解決此問題。
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...")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383206.html
