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

如何让TypeScript编译器识别全局类型?

解决全局接口在ts-node编译时无法识别的问题

步骤1:修复全局接口文件的语法与模块声明

你的globaltypes.ts存在两处关键问题:

  • 接口声明缺少interface关键字,TypeScript无法识别这是一个合法的接口定义
  • 若使用.ts文件而非.d.ts声明文件,必须将文件标记为模块(添加空导出),否则declare global的作用域无法全局生效

修改后的globaltypes.ts代码:

declare global {
  interface my_interface {
    name: string;
  }
}

// 标记为模块,确保全局声明作用域生效
export {};

更推荐的方式:将文件重命名为globaltypes.d.ts(TypeScript标准的全局类型声明文件格式),此时无需添加空导出,代码如下:

declare global {
  interface my_interface {
    name: string;
  }
}

步骤2:修复tsconfig.json的语法与配置错误

你的tsconfig.json存在语法错误(属性缺少逗号分隔),同时typeRoots配置需要调整以适配全局类型文件:

修改后的tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "baseUrl": "./",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    // 指定全局类型文件所在目录,包含根目录与默认的@types
    "typeRoots": ["./", "./node_modules/@types"],
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "./build/**/*"],
  "include": ["./**/*.ts", "./**/*.d.ts"]
}
  • 补充"./**/*.d.ts"到include数组,确保TypeScript识别所有.d.ts声明文件
  • 修复了所有属性后的逗号分隔问题,避免配置文件解析失败

步骤3:验证编译效果

完成上述修改后,重新运行ts-node编译,此时编译器将正确识别my_interface全局接口,你无需在其他文件中导入即可直接使用该接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:10:29