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

TypeScript中如何将模块扩展提升至包作用域?

问题解决:TypeScript外部库模块扩展移至.d.ts后失效

错误原因

你当前写法的核心问题有两个:

  • 包含import语句的.d.ts会被TypeScript视为模块文件,而非全局声明文件,此时嵌套在declare global中的模块扩展无法被正确识别。
  • 扩展外部库的模块无需包裹在declare global中,错误的作用域嵌套直接导致扩展失效。

正确写法

写法1:使用import type(TypeScript 3.8+)

直接在模块作用域下声明外部库扩展,用import type导入类型,既获取类型信息,又避免文件被标记为模块后干扰声明作用域:

// global.d.ts
import type { MyType } from "elsewhere";

declare module "@some/library" {
    interface LibraryType extends MyType {}
}

写法2:使用类型导入表达式

如果无法使用import type,可以通过import()在扩展内部直接引用目标类型:

// global.d.ts
declare module "@some/library" {
    interface LibraryType extends import("elsewhere").MyType {}
}

额外注意

确保你的.d.ts文件被tsconfig.json的include数组包含,否则TypeScript编译器不会处理该文件:

{
  "include": ["src/**/*", "global.d.ts"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:03:13