declare

Declare

声明文件

什么是声明文件

声明文件就是给js代码补充类型标注. 这样在ts编译环境下就不会提示js文件”缺少类型”.

声明文件以.d.ts结尾,一般放在根目录下

查看库的声明文件

1
2
// 以 jquery 为例
npm i @types/jquery

安装后, 我们可以在node_modules/@types/jquery中的看到声明文件

如果找不到,就需要自己手写了

怎么写声明文件

全局声明

declare

通过declare我们可以标注js全局变量的类型.

1
2
3
4
5
6
7
8
9
10
11
// global.d.ts
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
// global.d.ts
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{}字样
// 不然会报错❌: 全局范围的扩大仅可直接嵌套在外部模块中或环境模块声明中
export {}

现在String类型在vscode的语法提示下多了一个hump的方法,不过我们只是声明, 并没有用js实现, 所以运行会报错。

模块声明

什么是模块声明

npm下载的”包”自带了声明文件, 如果我们需要对其类型声明进行扩展就可以使用”declare module“语法。

例子

1
2
// main.ts
app.config.globalProperties.$axios = axios;

功能上我们实现了”this.axios”,但是ts并不能自动推断出我们添加了axios”, 所以添加如下声明文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// global.d.ts

// axios的实例类型
import { AxiosInstance } from 'axios'

// 声明要扩充@vue/runtime-core包的声明.
// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
declare module '@vue/runtime-core' {

// 给`this.$http`提供类型
interface ComponentCustomProperties {
$axios: AxiosInstance;
}
}
复制代码

这里扩充”ComponentCustomProperties“接口, 因为他是vue3中实例的属性的类型.

参考

本文绝大部分内容来源于下面两篇文章

https://juejin.cn/post/6844903993727008776

https://juejin.cn/post/7008710181769084964


declare
http://example.com/2022/08/12/declare/
Author
John Doe
Posted on
August 12, 2022
Licensed under