Declare
声明文件
什么是声明文件
声明文件就是给js代码补充类型标注. 这样在ts编译环境下就不会提示js文件”缺少类型”.
声明文件以.d.ts
结尾,一般放在根目录下。
查看库的声明文件
安装后, 我们可以在node_modules/@types/jquery
中的看到声明文件
如果找不到,就需要自己手写了
怎么写声明文件
全局声明
declare
通过declare
我们可以标注js全局变量的类型.
1 2 3 4 5 6 7 8 9 10 11
| declare var n: number; declare let s: string; declare const o: object; declare function f(s: string): number; declare enum dir { top, right, bottom, left }
|
使用
1 2 3 4 5 6 7 8 9
| n = 321 s = '文字' let o1 = o; f('123').toFixed(); dir.bottom.toFixed();
n = '312' s = 123g'yo是哟个
|
declare namespace
这个namespace
代表后面的全局变量是一个对象
1 2 3 4 5 6
| declare namespace MyPlugin { var n:number; var s:string; var f:(s:string)=>number; }
|
使用
1 2 3 4 5 6 7 8
| MyPlugin.s.substr(0,1); MyPlugin.n.toFixed(); MyPlugin.f('文字').toFixed();
MyPlugin.s.toFixed(); MyPlugin.n.substr(0,1); MyPlugin.f(123);
|
修改已存在的全局声明
node_modules/typescript/lib
下,有很多系统变量的声明文件
如果你要修改已存在的全局变量的声明可以这么写
1 2 3 4 5 6 7 8
| declare global { interface String { hump(input: string): string; } }
export {}
|
现在String
类型在vscode的语法提示下多了一个hump
的方法,不过我们只是声明, 并没有用js实现, 所以运行会报错。
模块声明
什么是模块声明
npm下载的”包”自带了声明文件, 如果我们需要对其类型声明进行扩展就可以使用”declare module“语法。
例子
1 2
| app.config.globalProperties.$axios = axios;
|
功能上我们实现了”this.axios”,但是ts并不能自动推断出我们添加了axios”, 所以添加如下声明文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
import { AxiosInstance } from 'axios'
declare module '@vue/runtime-core' { interface ComponentCustomProperties { $axios: AxiosInstance; } } 复制代码
|
这里扩充”ComponentCustomProperties“接口, 因为他是vue3中实例的属性的类型.
本文绝大部分内容来源于下面两篇文章
https://juejin.cn/post/6844903993727008776
https://juejin.cn/post/7008710181769084964