TS扩展全局变量类型推导
写这篇文章是因为我在学习vben项目时,在global文件的定义时出现了种种问题,但是在网上又不能及时找到合适的对策
前提概念
操作
然后我们定义一个global.d.ts
文件
这是我们定义好了全局的一些变量推导,但是我们ts的检查显示我们出现了一些问题,以下为具体的报错信息
Augmentations for the global scope can only be directly nested in external modules or ambient module declarations
这里的报错是说全局作用域的只能被直接嵌套在内部模块或者已经存在的模块定义文件中
显然我们是想定义一个定义文件的
在TS官网有这样的一段话
https://www.typescriptlang.org/docs/handbook/2/modules.html#non-modules
Before we start, it’s important to understand what TypeScript considers a module. The JavaScript specification declares that any JavaScript files without an
export
or top-levelawait
should be considered a script and not a module.…
If you have a file that doesn’t currently have any
import
s orexport
s, but you want to be treated as a module, add the line:
因此我们可以在文件的第一行加上export {}
但是这是我们仍然存在报错
A 'declare' modifier cannot be used in an already ambient context.ts(1038)
这里的意思是我们在一个已经存在的模块中使用了declare
,其实也很容易明白,因为global
作用域作用在全局,应该是一个内置的模块
那么现在我想到的就有两种方案:
- 删除
declare
(我认为的正确做法) tsconfig.json
文件配置skipLibCheck: true
skipLibCheck链接(vben中采用的方式)
如果采用第一种方案,此时已经可以得到正确结果
如果使用第二种方案,这个时候在我们的文件中仍然不能正确的找到推到结果
产生这个的原因与我的文件结构和tsconfig.json
配置有关
目录结构
因此我们要在tsconfig.json
中的include
中加入我们对全局可以引用的文件
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "build/**/*.ts", "types/**/*.d.ts"]
然后开启skipLibCheck
消除报错,就可实现推导了
原文链接:https://sunboyzgz.github.io/2021/05/20/typescript-global/
如有帮助,可以点赞让更多的人看到