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

Angular扩展Array.prototype.firstOrDefault运行报错:firstOrDefault is not a function

问题解决步骤

1. 确保扩展文件被加载

Angular不会自动加载未被任何模块/代码引用的文件,哪怕你加了export {}。必须在全局或模块中显式引入:

  • 在shared.module.ts中添加引入:
import './prototypes/linq.ts';
  • 或者在项目入口main.ts中全局引入:
import './app/shared/prototypes/linq.ts';

2. 修正类型定义错误

你的接口声明中返回类型错误,firstOrDefault返回单个元素而非数组,同时参数类型应更精确以保证类型安全:

declare global {
  interface Array<T> {
    firstOrDefault(predicate: (item: T) => boolean): T | null;
  }
}

3. 优化实现逻辑(可选但更高效)

原reduce实现会遍历所有元素,改用find方法更高效,逻辑也更清晰:

if (!Array.prototype.firstOrDefault) {
  Array.prototype.firstOrDefault = function<T>(this: T[], predicate: (item: T) => boolean): T | null {
    return this.find(predicate) ?? null;
  }
}

4. 验证tsconfig配置

确保tsconfig.json的include包含你的扩展文件:

"include": [
  "src/**/*.ts"
]

同时tsconfig.app.json的exclude不要排除该文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:58:16