YouTip LogoYouTip

Ts Ambient

Declaration files act as "translators" between TypeScript and JavaScript libraries. They tell TypeScript what features a JavaScript library exposes, what types its parameters are, and what types its return values are. * * * ## Starting with a Problem Suppose you are writing a project in TypeScript and need to introduce a third-party JavaScript library (like jQuery). You might write code like this: $('#foo');// or jQuery('#foo'); This code works perfectly fine in a pure JavaScript project, but it will throw an error directly in a TypeScript file: jQuery('#foo');// index.ts(1,1): error TS2304: Cannot find name 'jQuery'. Why does it throw an error? Because TypeScript doesn't recognize what `$` and `jQuery` are. TypeScript's core functionality is type checkingβ€”it needs to know the type of every variable and function during the compilation phase. However, jQuery is a pure JavaScript library with no type information, so TypeScript naturally cannot understand it. * * * ## Quick Fix: The `declare` Keyword The simplest way is to use the `declare` keyword to manually tell TypeScript: "This variable exists, and its type is like this": declare var jQuery: (selector: string) => any; jQuery('#foo'); This line of code means: declare a variable `jQuery`, which is a function that accepts a parameter of type `string` and returns a value of any type (`any`). Now TypeScript won't throw an error because the compiler already knows the type of `jQuery`. > Types declared with the `declare` keyword only take effect during the compilation phase. They are completely removed from the compiled JavaScript code and do not affect runtime behavior. The compiled JavaScript code for the above example is: jQuery('#foo'); You can see that the `declare` statement disappears, leaving only the actual calling code. However, `declare` can only solve temporary problems in a single file. If a library has many methods and classes, manually writing `declare` in every file is obviously impractical. This is where declaration files come into play. * * * ## Declaration Files: A One-Time Solution A declaration file consolidates all `declare` statements into a single separate file that any TypeScript file in the project can reference. ### File Naming Convention Declaration files uniformly use the `.d.ts` suffix, where `d` stands for "declaration". For example: .d.ts ### Basic Syntax The syntax for declaring a module is as follows: declare module Module_Name {} In TypeScript files, declaration files are introduced using triple-slash directives: /// Triple-slash directives are TypeScript-specific syntax used to tell the compiler to include the specified declaration file during compilation. > Declaration files for many popular third-party libraries (like jQuery, Lodash) are already maintained by the community and stored in the (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jquery/index.d.ts) project. You can use them by simply installing the corresponding `@types/xxx` package via npm, without needing to write them manually. * * * ## Complete Example: Creating a Declaration File from Scratch The following complete example demonstrates the entire process of creating and using a declaration file. The entire process involves the following files: | File | Purpose | | --- | --- | | CalcThirdPartyJsLib.js | Third-party JavaScript library (pure JS, no type information) | | Calc.d.ts | Declaration file (manually written, describing the library's types) | | CalcTest.ts | TypeScript business code (references the declaration file, calls the library) | | CalcTest.js | Compiled output (JS file compiled by tsc) | | .html | Final page running in the browser | ### Step 1: Create the Third-Party JavaScript Library Suppose we have a third-party library that provides a summation function. It uses the `` namespace to organize code and avoid variable name conflicts: ## CalcThirdPartyJsLib.js File Code: // File path: CalcThirdPartyJsLib.js // This is a simulated third-party JavaScript library // Declare the namespace variable (create an empty object if it doesn't exist) var ; // Use an Immediately Invoked Function Expression (IIFE) to encapsulate code, preventing internal variables from leaking into the global scope (function(){ // Calc constructor function for creating calculator objects var Calc =(function(){ function Calc(){ // No initialization parameters needed for now; keep the constructor for future extensions } }) // doSum method: calculates the sum of all integers from 0 to limit // limit (required): the upper limit of the summation, inclusive // Example: when limit=10, calculates 0+1+2+...+10 = 55 Calc.prototype.doSum=function(limit){ var sum =0; for(var i =0; i The main difference between a declaration file and a regular `.ts` file: a declaration file only has type signatures, no implementation code. It only answers "what does this function look like," not "what does this function do." ### Step 3: Use It in TypeScript Code Now write the business code. After referencing the declaration file, you can use this third-party JS library just like a native TypeScript library: ## CalcTest.ts File Code: // File path: CalcTest.ts // Triple-slash directive: tells the TypeScript compiler to include the declaration file /// // Create a Calc instance; TypeScript can now correctly recognize the type of `obj` var obj =new .Calc(); // obj.doSum("Hello"); // Compilation error! "Hello" is a string, but doSum requires a number console.log(obj.doSum(10));// Correct call: pass 10, expect to get 55 Note the commented-out line: obj.doSum("Hello"); If you uncomment this line, TypeScript will throw a compilation error because the declaration file has already specified that `doSum` only accepts a parameter of type `number`. This is type checking protecting youβ€”the error is exposed when writing the code, rather than crashing at runtime in the browser. ### Step 4: Compile the TypeScript Use the `tsc` command that comes with TypeScript to compile: tsc CalcTest.ts After compilation, a `CalcTest.js` file will be generated with the following content: ## CalcTest.js Compiled Output: // File path: CalcTest.js (automatically generated by the tsc command) /// var obj =new .Calc(); //obj.doSum("Hello"); // Compilation error console.log(obj.doSum(10));// Runtime result: outputs 55 in the console You can see that the triple-slash directive and the type information from the declaration file are gone in the compiled output, leaving only pure JavaScript runtime code. ### Step 5: Run in the Browser Finally, create an HTML page to link all the JS files together: ## Example

Declaration File Test

test.

Open this HTML file in a browser, open the console (F12), and you can see the output: 55 This is the return value of `doSum(10)`: 0+1+2+...+10 = 55. ![Image 1: Declaration File Test Result](#) * * * ## Summary A declaration file is essentially a "type manual" that allows TypeScript to understand and check pure JavaScript libraries. The entire workflow can be summarized in three steps: 1. Obtain a JS library and analyze what APIs it exposes. 2. Write a `.d.ts` declaration file describing the type signatures of these APIs. 3. Reference the declaration file in your TypeScript code to enjoy full type-checking protection. > For commonly used third-party libraries in daily development, most already have ready-made declaration files (installed via `npm install @types/xxx`). You only need to manually write declaration files when using very obscure libraries or internal private libraries.
← Jsref RepeatTs Namespace β†’