目的:引入一个 js 库的时候,TS 不能理解 js 编写的方法,所以需要描述文件(d.ts)来帮助 ts 去理解。

初始化

将拿jquery来进行举例,先看下目录吧:
TypeScript
|—-src
|—-index.html
|—-page.ts
|—-node_modules
|—-package.json

package.json

  1. {
  2. ...
  3. "scripts": {
  4. "start": "parcel ./src/index.html"
  5. }
  6. ...
  7. }

开始体验描述文件

理解其意

page.ts

  1. $(function () {
  2. });

现在 page.ts 文件肯定是报错的,找不到 $。我们在 src目录 下新建 jquery.d.ts ,里面声明一个全局变量(语法:declare):

  1. // 定义全局变量
  2. declare var $: (param: () => void) => void;

还可以定义全局函数

  1. // 定义全局函数
  2. declare function $(params: () => void): void;

函数重载

此时略微改动下代码,page.ts :

  1. $(function () {
  2. $("body").html("<div>123</div>");
  3. });

此时又会报错,之前定义的 $ 函数里并没有定义值,而且没有 html 函数方法,继续添加 jquery.d.ts 文件内容:

  1. // 定义全局函数
  2. declare function $(params: () => void): void;
  3. // 函数重载:一个函数名字可以定义多个函数。根据传递的参数不同,来进行理解函数
  4. declare function $(
  5. params: string
  6. ): {
  7. html: (html: string) => {};
  8. };

那现在 page.ts 文件就不会报错

interface 进行优化

  1. // 定义全局函数
  2. interface jqueryInstance {
  3. html: (html: string) => jqueryInstance;
  4. }
  5. // 函数重载
  6. declare function $(readyFunc: () => void): void;
  7. declare function $(selector: string): jqueryInstance;

interface 进行函数重载

  1. // 定义全局函数
  2. interface jqueryInstance {
  3. html: (html: string) => jqueryInstance;
  4. }
  5. // 使用 interface 的语法,实现函数重载
  6. interface jQuery {
  7. (readyFunc: () => void): void;
  8. (selector: string): jqueryInstance;
  9. }
  10. declare var $: jQuery;

对象、类的类型定义,以及命名空间嵌套

改写 page.ts :

  1. $(function () {
  2. $("body").html("<div>123</div>");
  3. new $.fn.init();
  4. });

改写 jquery.d.ts

  1. // 定义全局函数
  2. interface jqueryInstance {
  3. html: (html: string) => jqueryInstance;
  4. }
  5. // 函数重载
  6. declare function $(readyFunc: () => void): void;
  7. declare function $(selector: string): jqueryInstance;
  8. // 如何对对象进行类型定义,以及对类进行类型定义,以及命名空间的嵌套
  9. declare namespace $ {
  10. namespace fn {
  11. class init {}
  12. }
  13. }

ES6 模块化

不再使用cdn的方式引入jquery,改用npm包的形式
page.ts,引入jQuery会提示:没有jQuery模块的声明文件

  1. import $ from "jquery";
  2. $(function () {
  3. $("body").html("<div>123</div>");
  4. new $.fn.init();
  5. });

jquery.d.ts:模块化定义 jquery,里面添加 $ ,最后讲 $ 导出

  1. declare module "jquery" {
  2. interface jqueryInstance {
  3. html: (html: string) => jqueryInstance;
  4. }
  5. // 混合类型
  6. function $(readyFunc: () => void): void;
  7. function $(selector: string): jqueryInstance;
  8. namespace $ {
  9. namespace fn {
  10. class init {}
  11. }
  12. }
  13. export = $;
  14. }