typeScript 类型声明书写

1,236 阅读1分钟

什么是类型声明文件

  • 如果引入一些JS的包,例如jquery,TS编译器会因为找不到$而报错,这个时候就需要类型声明文件声明$

  • 声明文件主要分为全局声明和对模块的声明

全局声明

  • index.html

    <html>
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width">
            <title>Document</title>
            <!-- 引进CDN的jquery -->
            <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
            <script src='./index.js'></script>
        </head>
        <body></body>
    </html>
    
  • index.ts

    $(function(){
        $('body').html('<div>111<div>');
        new $.fn.init();
    });
    
  • jquery.d.ts

    // 因为jquery是全局引入的,所以我们必须要有一个全局的类型声明
    interface JqueryInstance {
        html: (html: string) => JqueryInstance
    }
    
    // 使用函数重载实现jquery,declare 定义的类型只会用于编译时的检查,编译结果中会被删除
    declare function $(params: () => void): void;
    declare function $(params: string): JqueryInstance;
    declare namespace $ {
        namespace fn {
            class init {}
        }
    }
    

局部声明

  • index.html

    <html>
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width">
            <title>Document</title>
            <script src='./index.js'></script>
        </head>
        <body></body>
    </html>
    
  • index.ts

    // npm install jquery 加载依赖
    import jquery from 'jquery';
    
    $(function(){
        $('body').html('<div>111<div>');
        new $.fn.init();
    });
    
  • jquery.d.ts

    // 因为jquery是全局引入的,所以我们必须要有一个全局的类型声明
    interface JqueryInstance {
        html: (html: string) => JqueryInstance
    }
    // 进行模块化的声明,这个时候必须导出
    declare module 'jquery' {
        interface JqueryInstance {
            html: (html: string) => JqueryInstance
        }
        /* 混合类型 */
        function $(params: () => void): void;
        function $(params: string): JqueryInstance;
        namespace $ {
            namespace fn {
                class init {}
            }
        }
        export = $;
    }