# 编写类型定义文件
在引入一些第三方库的时候需要引入其类型定义文件@types/xxx,但是在一些第三方库是没有类型定义文件的。
我们以jquery为例子,类型定义文件为xx.d.ts
# 描述文件中的全局类型
// 定义全局变量
// declare var $: (param: () => void) => void;
// 定义全局函数
interface JqueryInstance {
html: (html: string) => {};
}
//函数重载
declare function $(readyFunc: () => void): void;
declare function $(selector: string): JqueryInstance;
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 使用接口语法描述全局类型
// 定义全局函数
interface JqueryInstance {
html: (html: string) => {};
}
//使用interface的语法,实现函数重载
interface JQuery {
(readyFunc: () => void): void;
(selector: string): JqueryInstance;
}
declare var $:JQuery;
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 模块代码的类型描述文件
// Es6 模块化
declare module 'jquery' {
interface JqueryInstance {
html: (html: string) => JqueryInstance;
}
// 混合类型
function $(readyFunc: () => void): void;
function $(selector: string): JqueryInstance;
namespace $ {
namespace fn {
class init {}
}
}
export = $;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import $ from 'jquery';
$(function() {
$('body').html('<div>123</div>');
new $.fn.init();
});
1
2
3
4
5
6
7
2
3
4
5
6
7
此时引入jq就不会报错了
← 装饰器基础语法 ts在react中的使用 →