TypeScript声明文件

声明文件简介

当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。

什么是声明语句

假如我们想使用第三方库 jQuery,一种常见的方式是在 html 中通过 <script> 标签引入 jQuery,然后就可以使用全局变量 $jQuery 了。如:

$('body')

但是在 ts 中,编译器并不知道 $jQuery 是什么东西:

$('body') //Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.

这时,我们需要使用 declare var 来定义它的类型:

declare var $: (selector: string) => any;
$('body')

declare var 并没有真的定义一个变量,只是定义了全局变量 $ 的类型,仅仅会用于编译时的检查,在编译结果中会被删除。

什么是声明文件

通常我们会把声明语句放到一个单独的文件(index.d.ts)中,这就是声明文件:

interface myInfoType {
    name?: string;
    age?: number;
    [params:string]: any;
}
declare const myInfo: myInfoType;
declare const $: (selector: string) => any;

声明文件必须以.d.ts为后缀。

ts 会解析项目中所有的 *.ts 文件,当然也包含以 .d.ts 结尾的文件。所以当我们将 jQuery.d.ts 放到项目中时,其他所有 *.ts 文件就都可以获得 $ 的类型定义了。

├── src # 业务资源文件目录
│	├── category //项目分类
│	│	├── demo1
│	│	├── demo2
│	│	└── ...
│	├── components //公共组件
│	├── util //公共资源
│	└── custom.d.ts //项目全局变量声明文件
├── index.html //项目启动入口
├── .gitignore //git忽略文件
├── .eslintrc.js //eslint校验配置
├── package.json //依赖包
├── tsconfig.json //ts配置
├── webpack.config.build.js //webpack打包
├── webpack.config.base.js //webpack基础配置
└── webpack.config.js //项目启动配置

假如仍然无法解析,那么可以检查下 tsconfig.json 中的 filesincludeexclude 配置,确保其包含了 index.d.ts 文件。

也是就是说声明文件要代码使用的顶级目录下。

第三方声明文件

我们可以直接下载下来使用,但是更推荐的是使用 @types 统一管理第三方库的声明文件。

@types 的使用方式很简单,直接用 npm 安装对应的声明模块即可,以 jQuery 举例:

npm install @types/jquery --save-dev

书写声明文件

在不同的场景下,声明文件的内容和使用方式会有所区别。

库的使用场景主要有以下几种:

全局变量

使用全局变量的声明文件时,如果是以 npm install @types/xxx --save-dev 安装的,则不需要任何配置。否则就需要在声明文件中声明全局变量。

全局变量的声明文件主要有以下几种语法:

declare var/const/let

用来定义一个全局变量的类型;

interface myInfoType {
    name?: string;
    age?: number;
    [params:string]: any;
}
declare var myInfo:myInfoType;
declare let myInfo:myInfoType;
declare const myInfo:myInfoType; //此时全局变量是一个常量不允许修改

一般来说,全局变量都是禁止修改的常量,所以大部分情况都应该使用 const 而不是 varlet

需要注意的是,声明语句中只能定义类型,切勿在声明语句中定义具体的实现

declare const test = function(para) {
    return para;
}
//An implementation cannot be declared in ambient contexts.

declare function

declare function 用来定义全局函数的类型。

declare function test(para: string):any;

统一也是只能定义类型 不能定义具体实现;

declare function test(para: string):any{
    return para;
}
//An implementation cannot be declared in ambient contexts.ts(1183)

declare class

当全局变量是一个类的时候,我们用 declare class 来定义它的类型

declare class student {
    name: string;
    constructor(name: string);
    hello(): string;
}

同样的,declare class 语句也只能用来定义类型,不能用来定义具体的实现,比如定义 hello` 方法的具体实现则会报错:

declare class student {
    name: string;
    constructor(name: string);
    hello(){
        return this.name;
    };
}
//An implementation cannot be declared in ambient contexts.ts(1183)

declare namespace

namespace 是 ts 早期时为了解决模块化而创造的关键字,中文称为命名空间。

随着 ES6 的广泛应用,现在已经不建议再使用 ts 中的 namespace,而推荐使用 ES6 的模块化方案了,故我们不再需要学习 namespace 的使用了。

namespace 被淘汰了,但是在声明文件中,declare namespace 还是比较常用的,它用来表示全局变量是一个对象,包含很多子属性。

declare namespace jQuery {
    function ajax(url: string, settings?: any): void;
}

interface 和 type

除了全局变量之外,可能有一些类型我们也希望能暴露出来。在类型声明文件中,我们可以直接使用 interfacetype 来声明一个全局的接口或类型

interface fetchOptions {
    method?: 'GET' | 'POST';
    credentials?: string;
    headers?: any;
    [params: string]: any;
}
let options: fetchOptions = {
    method: 'GET',
    credentials: 'include'
}
防止命名冲突

暴露在最外层的 interfacetype 会作为全局类型作用于整个项目中,我们应该尽可能的减少全局变量或全局类型的数量。故最好将他们放到 namespace

declare namespace fetchSetting {
    interface fetchOptions {
        method?: 'GET' | 'POST';
        credentials?: string;
        headers?: any;
        [params: string]: any;
    }
}
let options: fetchSetting.fetchOptions = {
    method: 'GET',
    credentials: 'include'
}
发布了58 篇原创文章 · 获赞 78 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/gongch0604/article/details/99577401