TypeScript 无法导入自定义 .d.ts 声明文件中导出的类型如何解决?
解决方法
核心错误原因
- 导入路径不符合相对路径规则
- .d.ts 中错误声明了常量而非类型
具体修改步骤
1. 修正 .d.ts 中的类型声明
你当前写的 declare const 是用于声明全局常量值的语法,若要定义可导入的类型,应该使用 type 或 interface 关键字:
// file.d.ts 正确写法 export type DataConverted = { low: number, high: number, open: number, close: number, openTime: number, volume: number } export type ChartRefPoints = { highestVal? : number, lowestVal?: number, maxTime? : number, minTime? : number, maxVolume? : number, minVolume? : number }
2. 修正导入语句
同目录下的文件导入需要使用相对路径前缀 ./,同时建议使用 import type 专门导入类型,避免编译后残留无效导入语句:
// file.tsx 正确导入写法 import type { DataConverted, ChartRefPoints } from "./file";
3. 异常排查(如果修改后仍报错)
检查项目根目录的 tsconfig.json 配置:
include配置项需要包含你的.d.ts文件所在目录,例如项目源码都在src目录下,需要配置"include": ["src/**/*"]moduleResolution配置项建议设置为"Node"或"NodeNext",保证相对路径可以正常解析
内容的提问来源于stack exchange,提问作者mouchin777
相关产品推荐
相关产品推荐

