访问数组索引时如何强制打字稿给出错误

Posted

技术标签:

【中文标题】访问数组索引时如何强制打字稿给出错误【英文标题】:How to enforce typescript to give error when accessing array index 【发布时间】:2022-01-20 00:35:44 【问题描述】:
interface ApiResponse
  data: Student[];


interface Student 
  name: string;

举个例子,我 100% 确定我会得到 data,但如果 data 是一个空数组,则会产生运行时错误。

const response = await fetch(...);
response.data[0].name

Uncaught TypeError: Cannot read properties of undefined (reading 'name')

我希望打字稿警告我可能出现的空数组情况。我知道我可以写它response.data[0]?.name,但如果团队中的某个人不使用?,我们将不知道潜在的未定义。

【问题讨论】:

【参考方案1】:

我想这意味着数据可以是空数组,可以有学生,也可以有未定义的。这迫使我在这种情况下使用?,这是我的目标。

interface ApiResponse
  data: (Student|undefined)[];

【讨论】:

【参考方案2】:

您的答案提供了一种处理带有undefined 元素的数组的方法。但是这如何处理空数组场景呢?您的回答再次迫使您在问题中添加? like 来解决这个问题。

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...")

【讨论】:

以上是关于访问数组索引时如何强制打字稿给出错误的主要内容,如果未能解决你的问题,请参考以下文章

数组中的展开操作出错。 TS1005:“,”预期。打字稿

来自数组类型的打字稿接口

使用打字稿反应 redux combinereducer 时出错

查找累积和反应打字稿

在打字稿中导入 javascript 库时出错

打字稿从元组/数组值派生联合类型