TypeScript declaration file

Posted by Celadon on Wed, 14 Aug 2019 10:32:26 +0200

Introduction to Statement Document

When using a third-party library, we need to refer to its declaration file in order to obtain the corresponding code completion, interface prompts and other functions.

What is a declarative statement

If we want to use the third-party library jQuery, a common way is to introduce jQuery in html through the < script > tag, and then we can use the global variable $or jQuery. Such as:

$('body')

But in ts, the compiler doesn't know what $or jQuery is:

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

At this point, we need declare var to define its type:

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

declare var does not really define a variable, but defines the type of global variable $and is only used for compile-time checks, which are deleted from the compiled results.

What is a declaration file?

Usually we put the declaration statement in a separate file (index.d.ts), which is the declaration file:

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

The declaration file must be suffixed with. d.ts.

TS parses all *. TS files in the project, and of course includes files ending with. d.ts. So when we put jQuery.d.ts into the project, all other *. TS files can get the type definition of $.

├── src # Business Resource File Directory
│	├── category //Item classification
│	│	├── demo1
│	│	├── demo2
│	│	└── ...
│	├── components //Common components
│	├── util //public resource
│	└── custom.d.ts //Project global variable declaration file
├── index.html //Project startup entry
├── .gitignore //git ignores files
├── .eslintrc.js //eslint verification configuration
├── package.json //Dependency packages
├── tsconfig.json //ts configuration
├── webpack.config.build.js //Web pack packaging
├── webpack.config.base.js //Web pack infrastructure configuration
└── webpack.config.js //Project startup configuration

If it is still not parsable, check the files, include, and exclude configurations in tsconfig.json to ensure that it contains the index.d.ts file.

That is to say, the top-level directory where the declaration file is to be used by the code.

Third party declaration document

We can download and use it directly, but it is more recommended to use @types to manage declaration files of third-party libraries in a unified way.

@ The use of types is simple. Install the corresponding declaration module directly with npm. Take jQuery as an example:

npm install @types/jquery --save-dev

Writing Declaration Documents

In different scenarios, the content and usage of the declaration file will be different.

The usage scenarios of libraries are as follows:

global variable

When using declaration files for global variables, no configuration is required if installed as NPM install@types/xxx -- save-dev. Otherwise, you need to declare global variables in the declaration file.

The declaration files of global variables have the following grammars:

declare var/const/let

Used to define the type of a global variable;

interface myInfoType {
    name?: string;
    age?: number;
    [params:string]: any;
}
declare var myInfo:myInfoType;
declare let myInfo:myInfoType;
declare const myInfo:myInfoType; //At this point, the global variable is a constant that cannot be modified.

Generally speaking, global variables are constants that are not allowed to be modified, so const should be used in most cases instead of var or let.

It is important to note that only types can be defined in declaration statements, and that specific implementations should not be defined in declaration statements.

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

declare function

declare function is used to define the type of global function.

declare function test(para: string):any;

Unification can only define types but not specific implementations.

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

declare class

When a global variable is a class, we use declare class to define its type.

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

Similarly, declare class statements can only be used to define types, not specific implementations. For example, specific implementations of defining hello `methods can cause errors:

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 is a key word created in the early days of ts to solve modularity, which is called namespace in Chinese.

With the wide application of ES6, it is no longer recommended to use namespace in ts, but to use the modular scheme of ES6, so we no longer need to learn the use of namespace.

Namespace has been eliminated, but declare namespace is more commonly used in declaration files to indicate that a global variable is an object with many sub-attributes.

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

interface and type

In addition to global variables, there may be some types that we would like to expose. In a type declaration file, we can declare a global interface or type directly using interface or type.

interface fetchOptions {
    method?: 'GET' | 'POST';
    credentials?: string;
    headers?: any;
    [params: string]: any;
}
let options: fetchOptions = {
    method: 'GET',
    credentials: 'include'
}
Preventing Naming Conflict

Exposure to the outermost interface or type acts as a global type throughout the project, and we should minimize the number of global variables or types as much as possible. So it's better to put them under namespace.

declare namespace fetchSetting {
    interface fetchOptions {
        method?: 'GET' | 'POST';
        credentials?: string;
        headers?: any;
        [params: string]: any;
    }
}
let options: fetchSetting.fetchOptions = {
    method: 'GET',
    credentials: 'include'
}

Topics: JQuery npm JSON Webpack