You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular生产构建报错:Object.fromEntries及crop属性不存在问题求助

Angular生产构建报错解决方案

报错信息

执行构建命令:ng build --prod --base-href="." --aot --output-hashing=all时出现两个类型错误:

  1. property 'fromEntries' does not exist on type 'ObjectConstructor'
  2. Property 'crop' does not exist on type 'unknown'

本地开发运行无报错,仅AOT生产构建触发。


错误1:Object.fromEntries不存在的解决方法

原因

Object.fromEntries是ES2019新增的API,若你的TypeScript编译目标版本低于ES2019,AOT构建时会因不支持该API报错。

解决步骤

方案1:升级TypeScript编译目标

修改项目根目录下的tsconfig.json:

  • 将compilerOptions.target设置为ES2019或更高版本
  • 确保compilerOptions.lib数组包含ES2019或ES2019.Object

示例tsconfig.json片段:

{
  "compilerOptions": {
    "target": "ES2019",
    "lib": ["ES2019", "DOM"]
  }
}

方案2:自定义fromEntries替代函数

若无法升级编译目标,可手动实现该函数,避免依赖ES2019:

// 在组件或工具类中定义
function fromEntries<T>(entries: [string, T][]): Record<string, T> {
  return entries.reduce((obj, [key, val]) => {
    obj[key] = val;
    return obj;
  }, {} as Record<string, T>);
}

然后替换原代码中的Object.fromEntries为该函数:

const res = fromEntries(Object.entries(data).filter(([k,v]) => v.crop === 'Eiche' || v.crop === 'Kiefer'));

错误2:Property 'crop' does not exist on type 'unknown'的解决方法

原因

你将data声明为Object类型,TypeScript无法推断其内部结构,AOT构建的严格类型检查会阻止访问未声明的crop、eppo属性。另外,你更新后的代码直接调用data.filter是错误的——Object类型没有filter方法,filter是数组的方法。

解决步骤

  1. 定义数据类型接口:明确data内部每个子项的结构
// 在组件顶部或单独的类型文件中定义
interface CropItem {
  crop: string;
  eppo: string;
  // 补充其他需要用到的属性
}
  1. 修正类型声明与代码逻辑:给data指定正确的类型,恢复原有的键值对遍历逻辑(因为原data是对象而非数组)
this.subEvtEmitterForAllSubCultures = this._InsecticidesProductsPropertiesService.getEvtEmitterForResponseAllSubCultures().subscribe((data: Record<string, CropItem>)=>{
  // 过滤符合条件的项
  const filteredEntries = Object.entries(data).filter(([k, v]) => v.crop === 'Eiche' || v.crop === 'Kiefer');
  const res = Object.fromEntries(filteredEntries); // 或用自定义的fromEntries
  
  // 提取去重后的crop和eppo
  this.crops = Array.from(new Set(Object.values(res).map(item => item.crop)));
  this.eppos = Array.from(new Set(Object.values(res).map(item => item.eppo)));
});

内容的提问来源于stack exchange,提问作者Amrmsmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 08:23:11