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

如何正确导入并使用自定义扩展的TypeScript Array接口?

TypeScript扩展Array接口后无法导入的解决方法

问题描述

我在src/types/array.d.ts文件中扩展了Array接口并实现了polyfill:

export {}

declare global {
  interface Array<T> {
    binaryIndexOf(e: T, desc: boolean): number
    addSorted(e: T, desc: boolean): T[]
  }
}

if (!Array.prototype.binaryIndexOf) {
  Object.defineProperty(Array.prototype, 'binaryIndexOf', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function binaryIndexOf<T>(this: T[], e: T, desc: boolean) {
      // 方法实现...
    }
  });
  // addSorted方法的polyfill...
}

尝试通过import './types/array'或import {} from './types/array'导入时,出现错误:Error: Cannot find module './types/array'。我的tsconfig.json配置如下:

{
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "useUnknownInCatchVariables": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "target": "es5",
    "baseUrl": "src"
  }
}

请问如何正确导入并使用这个扩展后的Array接口?

解决步骤

1. 拆分类型声明与polyfill代码

你的array.d.ts同时包含类型声明和运行时代码,不符合TypeScript对类型文件的处理规则,建议拆分:

  • 保留src/types/array.d.ts作为纯类型声明文件:
declare global {
  interface Array<T> {
    binaryIndexOf(e: T, desc: boolean): number
    addSorted(e: T, desc: boolean): T[]
  }
}

export {};
  • 创建src/polyfills/array.ts单独存放polyfill实现:
if (!Array.prototype.binaryIndexOf) {
  Object.defineProperty(Array.prototype, 'binaryIndexOf', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function binaryIndexOf<T>(this: T[], e: T, desc: boolean) {
      // 完整方法实现
    }
  });
}

if (!Array.prototype.addSorted) {
  Object.defineProperty(Array.prototype, 'addSorted', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function addSorted<T>(this: T[], e: T, desc: boolean) {
      // 完整方法实现
    }
  });
}

2. 配置tsconfig.json自动识别类型

修改tsconfig.json,添加include和typeRoots配置,让TypeScript自动加载类型声明:

{
  "compilerOptions": {
    // 原有配置...
    "typeRoots": ["./src/types", "./node_modules/@types"],
    "include": ["src/**/*"]
  }
}

配置后,TypeScript会自动识别src/types下的所有.d.ts文件,无需手动导入类型声明。

3. 导入polyfill代码

在项目入口文件(如src/index.ts)中导入polyfill文件,确保应用启动时执行一次:

// 相对路径导入
import './polyfills/array';
// 或利用baseUrl的绝对路径导入
import 'polyfills/array';

polyfill修改全局Array原型后,任何地方都能直接调用array.binaryIndexOf()和array.addSorted()。

4. 检查路径与模块规范

  • 因开启了isolatedModules,所有文件必须是ES模块,拆分后的类型文件通过export {}成为模块,polyfill文件本身就是模块,符合要求。
  • 导入时避免路径拼写错误,利用baseUrl的绝对路径能减少路径问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:04:07