我有一个对象数组,每个对象都有不同的类型。
我正在使用 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 :\
最佳答案
您的结构强制 reportData
为 IReportItem
类型,即:IReportItemRegions
或 IReportItemFactionStatus
因为它是一个元素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/