TypeScript declaration file

Table of contents

1. TypeScript declaration file

1. The creation and simple use of TypeScript declaration files


1. TypeScript declaration file

1. The creation and simple use of TypeScript declaration files

As a superset of JavaScript, TypeScript inevitably needs to refer to other third-party JavaScript libraries during the development process. Although the classes and methods of the library can be called through direct references, the features of TypeScript such as type checking cannot be used. In order to solve this problem, it is necessary to remove the functions and method bodies in these libraries and only keep the export type declaration, and generate a declaration file describing JavaScript library and module information. By referencing this declaration file, various features of TypeScript can be borrowed to use the library file.

Create xiaoguai.js to define a third-party library

let SamXiaoguai;  
(function(SamXiaoguai) {
    let SamC = (function () { 
        function SamC() { 
        } 
    })
    SamC.prototype.samSpaek = function (oneStr) {
        return oneStr; 
    }
    SamXiaoguai.SamC = SamC; 
    return SamC; 
})(SamXiaoguai || (SamXiaoguai = {})); 
let samTest = new SamXiaoguai.SamC();

Declaration files end with .d.ts

Create a SamC.d.ts file and use declare module to declare a file or module

declare module SamXiaoguai {
    export class SamC {
        samSpaek(oneStr: string): string;
    }
}

Create a samTest file and import the declaration file

/// <reference path = "SamC.d.ts" /> 
let obj = new SamXiaoguai.SamC();
console.log(obj.samSpaek("Hello"));

Use tsc samTest.ts to compile and generate samTest.js

can be created by creating html using

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SamXiaoguai</title>
    <script src="xiaoguai.js"></script>
    <script src="samTest.js"></script>
</head>

<body>
    <script>
        let obj2 = new SamXiaoguai.SamC();
        console.log(obj2.samSpaek("Hello"));
        console.log(obj2.samSpaek("Ts"));
    </script>
</body>

</html>

Open the console to see the output as

Hello
Hello
Ts

If you have any questions, please comment below and I will answer them for you.

Guess you like

Origin blog.csdn.net/samxiaoguai/article/details/128443814