目的:引入一个 js 库的时候,TS 不能理解 js 编写的方法,所以需要描述文件(d.ts)来帮助 ts 去理解。
初始化
将拿jquery来进行举例,先看下目录吧:
TypeScript
|—-src
|—-index.html
|—-page.ts
|—-node_modules
|—-package.json
package.json
{..."scripts": {"start": "parcel ./src/index.html"}...}
开始体验描述文件
理解其意
page.ts
$(function () {});
现在 page.ts 文件肯定是报错的,找不到 $。我们在 src目录 下新建 jquery.d.ts ,里面声明一个全局变量(语法:declare):
// 定义全局变量declare var $: (param: () => void) => void;
还可以定义全局函数
// 定义全局函数declare function $(params: () => void): void;
函数重载
此时略微改动下代码,page.ts :
$(function () {$("body").html("<div>123</div>");});
此时又会报错,之前定义的 $ 函数里并没有定义值,而且没有 html 函数方法,继续添加 jquery.d.ts 文件内容:
// 定义全局函数declare function $(params: () => void): void;// 函数重载:一个函数名字可以定义多个函数。根据传递的参数不同,来进行理解函数declare function $(params: string): {html: (html: string) => {};};
interface 进行优化
// 定义全局函数interface jqueryInstance {html: (html: string) => jqueryInstance;}// 函数重载declare function $(readyFunc: () => void): void;declare function $(selector: string): jqueryInstance;
interface 进行函数重载
// 定义全局函数interface jqueryInstance {html: (html: string) => jqueryInstance;}// 使用 interface 的语法,实现函数重载interface jQuery {(readyFunc: () => void): void;(selector: string): jqueryInstance;}declare var $: jQuery;
对象、类的类型定义,以及命名空间嵌套
改写 page.ts :
$(function () {$("body").html("<div>123</div>");new $.fn.init();});
改写 jquery.d.ts
// 定义全局函数interface jqueryInstance {html: (html: string) => jqueryInstance;}// 函数重载declare function $(readyFunc: () => void): void;declare function $(selector: string): jqueryInstance;// 如何对对象进行类型定义,以及对类进行类型定义,以及命名空间的嵌套declare namespace $ {namespace fn {class init {}}}
ES6 模块化
不再使用cdn的方式引入jquery,改用npm包的形式
page.ts,引入jQuery会提示:没有jQuery模块的声明文件
import $ from "jquery";$(function () {$("body").html("<div>123</div>");new $.fn.init();});
jquery.d.ts:模块化定义 jquery,里面添加 $ ,最后讲 $ 导出
declare module "jquery" {interface jqueryInstance {html: (html: string) => jqueryInstance;}// 混合类型function $(readyFunc: () => void): void;function $(selector: string): jqueryInstance;namespace $ {namespace fn {class init {}}}export = $;}
