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

导入自定义.d.ts文件报错:File is not a module.ts(2306)

问题解决:TypeScript提示.d.ts文件不是模块

问题根源

你写的generated.d.ts用了declare namespace语法,这属于全局类型声明,不是标准的ES模块结构,所以TypeScript会报错“File is not a module”,没法用import导入。

两种解决办法

办法1:改成ES模块导出(推荐)

把generated.d.ts里的命名空间改成直接导出类型,符合现代TS模块化规范:

// generated.d.ts
export type CategoryData = {
  id: string;
  parent_id: string | null;
  name: string;
  slug: string;
  category_type: App.Enums.CategoryType;
  created_at: string;
  updated_at: string;
};

export type CategoryForm = {
  parent_id: string | null;
  name: string;
  category_type: App.Enums.CategoryType;
};

改完之后,原来的导入语句import type { CategoryForm } from '../../lib/types/generated';就能正常生效了。

如果需要保留App.DTO.Category的层级结构,可以用嵌套导出:

// generated.d.ts
export namespace App {
  export namespace DTO {
    export namespace Category {
      export type CategoryData = { /* 同上内容 */ };
      export type CategoryForm = { /* 同上内容 */ };
    }
  }
}

导入后使用方式:

import type { App } from '../../lib/types/generated';

// 使用类型
const form: App.DTO.Category.CategoryForm = { /* ... */ };

办法2:直接使用全局类型(不推荐)

如果非要保留declare namespace的写法,确保这个文件被TypeScript识别为全局类型(比如在tsconfig.json的include里包含它),然后直接在代码里用App.DTO.Category.CategoryForm,不需要写import语句。但这种方式容易引发命名冲突,不适合大型项目。

额外检查

确认tsconfig.json的include配置包含了你的类型文件路径:

{
  "include": ["src/**/*", "lib/**/*"]
}

同时确保module选项设置为ES模块相关值(比如ESNext、ES6),避免模块解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 19:18:20