javascript - typescript 在不同类型的数组中查找

我有一个对象数组,每个对象都有不同的类型。 我正在使用 Array.find(或 for 循环,没有区别)从数组中获取对象之一。现在 Typescript 无法理解我从数组中获取的类型,除非我添加额外的 || reportData.type !== "REGIONS" 检查。有没有其他办法解决?

 export interface IReportItemFactionStatus {
    type: "FACTION_STATUS";
  }

  export interface IReportItemRegions {
    type: "REGIONS";
    regions: [];
  }

  export type IReportItem = IReportItemRegions | IReportItemFactionStatus;

  export type IReport = Array<IReportItem>;

  // ... code ...
  // report has type IReport

  const reportData = report.find((d) => {
      return d.type === "REGIONS";
  });

  if (!reportData) {
    return [];
  }
  console.log(reportData.regions); // Typescript error here

但是如果我为 reportData.type 添加额外的检查,它就会开始正常工作

  if (!reportData || reportData.type !== "REGIONS") {
    return [];
  }
  console.log(reportData.regions); // No Typescript error here :\

最佳答案

您的结构强制 reportDataIReportItem 类型,即:IReportItemRegionsIReportItemFactionStatus 因为它是一个元素report 数组。

您想显示仅在接口(interface)IReportItemRegions 中实现的属性regions。我们不知道 reportData 是否属于 IReportItemRegions 类型。在尝试访问该属性之前,您必须确保您的对象实现了该属性:

if ('regions' in reportData) {
  console.log(reportData.regions)
}

如果您希望 TypeScript 推断类型,您必须摆脱 find 并重写您的代码。我有一个简单的实现:

let reportData: IReportItemRegions;
let i = 0;
while (!reportData && report.length < i) {
  const currentReportData = report[i];
  if (currentReportData.type === 'REGIONS') {
    // Typescrit knows currentReportData is of type IReportItemRegions
    reportData = currentReportData;
  }
  i++;
}

if (!reportData) {
  return [];
}
console.log(reportData.regions);

关于javascript - typescript 在不同类型的数组中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54248986/

相关文章:

r - 如何从 Shiny 中的 plotly 事件中获取方面数据

c++ - 如何在嵌入式 V8 中重置全局对象?

c# - 偷看后从并发队列中删除元素的模式

amazon-web-services - AWS Glue - 从现有笔记本服务器访问新的开发端点

bash - 如何以编程方式从 docker-compose.yml 中删除服务?

python - 如何读取 main_file.exe 中的 data.txt 而不将它们保存在 p

ios - 为 App Store 准备不同分辨率的 App Preview 视频

python-3.x - odoo 从代码向用户发送消息(通知)

vb.net - 按列 ("TagIndex = 5"搜索 dgv 列)

swift - 如何修复此 'required condition is false: format