Introduction and mastery of TypeScript - d. Use and explanation of TS description file

introduce

What is a description file? Before answering this question, let's first think about the problem. Typescript and javascript are not interlinked in principle. Can all javascript be used before typescript comes out, such as jQuery? If not, is it a pity? Therefore, in order to solve this problem, typescript has a description file, That's what we often see d.ts file, whose function is to get through javascript and typescript and describe the missing types for javascript files;

Taking jQuery as an example, the following describes how to use jQuery in typescript. If you don't understand it after reading it, please see my hammer!!! It doesn't recognize people!!!

initialization

For better and more intuitive learning, initialize a project first. Our purpose is to mix jQuery and typescript together
In short, the initialization command is as follows

// Initialize npm
npm init

// Initialize typescript
tsc --init

Then create an html file and a new one in the same directory ts file, introduce the cdn of jQuery into html, such as:

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <title></title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="" />
          
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        
				<script src="./demo.ts"></script>
    </head>
    <body></body>
    <html></html>
</html>

Or use Vue's scaffold to create a new Vue3+typescript project, and under its public, click index HTML introduces the cdn of jquery above

Description file

We'll take the d. The file ending with TS is called a description file. It doesn't matter what the previous text is, whether it's a.d.ts or jQuery d. TS is OK. Its function is to describe the types for js files;

This involves the first knowledge point, the keyword: declare, which represents a declaration, followed by the type of code that defines the type. See the specific analysis below

Define global variables

For example, we are now Write jquery code in ts file

;$(function() {})();

This is a common method of executing functions immediately in the jquery era, if we directly If it is written in ts, it will report an error. It will prompt you to install jq in @ types. The error is as follows:

Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i @types/jquery and then add jquery to the types field in your tsconfig

In fact, we don't have the type of jquery in types, so in order to make it available in ts works normally. We need to d.ts is declared in this description file:

declare const $: (param: () => void) => void;

Analyze this statement and make a split. The outer layer is as follows

$()	// This is a jquery function

Corresponding declaration

$:()=>void

Take a closer look, this should be understandable, statement this yes one individual letter number , and And it no have return return value , of after again see ginseng number , This is a function, and it has no return value. Look at the parameters later, This is a function and it has no return value. Then look at the parameter. A function() {} is nested in () and a function type should be nested in the corresponding declaration. Obviously, function() {} is a parameter of $(). This parameter is a function and it has no return value,

// Therefore, in the outer declaration, add a parameter and set the function type for it without return value

param: () => void

Define global functions

Take the example above

;$(function() {})();

This is obviously also a function, and we can also declare it in the form of a function

declare function $(params: () => void): void;

After the above analysis, this should be clear. It declares a function $, which has no return value, so it is void, but it has a parameter, which is a function and has no return value;

Here, some friends familiar with jQuery may ask that jQuery has other uses. For example, it can select a node and add content to it. The code is as follows

$(function() {
	$("body").append("<div>oliver</div>")
});

If it is written in this way, it will still report errors. Yes, it will continue to report errors because we are not in this way d.ts, so for this usage, we'll write a type description

// type
declare function $(
    params: string
): {
    append: (params: string) => {};
};

This time, the function of $() is a string, and its return value is unknown, but since it can be used Append means that it is at least an object. In js, there are only objects This operator immediately has an append method, which has a parameter and is a string;

It's almost easy to understand here. Let's do another exercise

$(function() {
    $(".tc-demo-container").css("background-color", "yellow");
});

How to write its type file, the answer is as follows

interface jQueryIntance {
    css: (paramA: string, paramB: string) => jQueryIntance;
}

declare function $(params: string): jQueryIntance;

This time, we separate the type and define it as an interface. There is an attribute named css on the interface. Its value is a function. It has two parameters. The type of the parameters is a string. In fact, this function has a return value. We know that its return value is a jquery object;

Interface override

After seeing the above exercise, did you find another way to write the description file? The description file can be defined using an interface,

// interface override
interface jQueryIntance {
    css: (paramA: string, paramB: string) => jQueryIntance;
    append: (paramA: string) => jQueryIntance;
}

declare const $: jQueryIntance;

Define global objects

In fact, the above two are introducing the definition of functions. How to define objects, or take jQuery as an example. We all know that when we use $, we actually execute new $. In jQuery fn. How to define the init method

// To be defined
new $.fn.init;

// To ensure that there is no conflict, you can use namespace to frame it
declare namespace $ {
    namespace fn {
        class init {}
    }
}

Take another example from a real project. For example, we wrote a tool function util similar to loadsh. We mounted it on the window object and used it in the following ways

util.add()

// perhaps
window.util.add()

At this time, typescript will report an error. It will report that util does not exist in the window. Therefore, we need to define its type in the description file. We can write this as follows

declare interface Window {
    util: {
        add: () => void;
    };
}

A Window is defined (note that Window is capitalized). There is an util object on it. There is an add method on this object. This method has no parameters and no return value;

Modular file declaration

In fact, in modern front-end development, especially after the rise of Vue and React, almost all large-scale projects are modular development, and the syntax used is ES6 module syntax. Take jquery for example

// Using jquery in modern frameworks
import $ from "jquery"

I think it's more written in this way now. If it's written in this way and there is no installation of types, then it's in d. How to describe and define types in TS;

Let's take a direct look at an example. The code is still the code above. Integrate it

// code
import $ from "jquery"

$("body").append("<div>oliver</div>")

new $.fn.init()

Corresponding, in d. This should be written in TS:

declare module "jquery" {
    function $(params: string): {
        append: (params: string) => {};
    };
    namespace $ {
        namespace fn {
            class init {}
        }
    }

    export = $;
}
,

We use the keyword: declare to describe a type. The type is module and the variable name is jquery. Note: the jquery after module is the same as the jquery after import. The content after is basically the same as that before. The difference lies in two points:

  1. The keyword declare is not needed internally, because it is not needed inside if it is described outside;
  2. If you want to use it externally, you must expose it. The way to expose it is export;

Summary

This article mainly describes how to use d.ts description file, its main function is to make up for some missing types, so that Javascript files can continue to be used in Typescript;

The main way is to use the keyword declare to describe various types, such as variables, objects, functions, etc. after the description is completed, Typescript can automatically identify them Corresponding variables, functions and objects in ts file;

Keywords: Javascript Front-end TypeScript

Added by cmos on Wed, 15 Dec 2021 06:16:27 +0200