Modules

TS Declaration Files

Creating Declaration Files

TypeScript declaration files (.d.ts) provide types for JavaScript libraries.

What Are TypeScript Declaration Files?

TypeScript declaration files, with the extension .d.ts, are crucial in providing type information about JavaScript libraries. They act as a bridge, allowing TypeScript to understand the types used in JavaScript code. These files enable developers to reap the benefits of TypeScript’s type-checking features even when dealing with pure JavaScript libraries.

Why Use Declaration Files?

Using declaration files offers several advantages:

  • Type Safety: They help prevent runtime errors by catching type-related issues at compile time.
  • IntelliSense: They enhance code editors with auto-completion, parameter info, and documentation, boosting productivity.
  • Documentation: They serve as a form of documentation for JavaScript libraries, clarifying function signatures and expected types.

Creating a Declaration File

To create a declaration file, you must define types for the JavaScript code you are using. Here's a simple example of how to create a declaration file for a JavaScript module:

In the example above, math-utils.d.ts declares the type signature for the add function defined in math-utils.js. This provides TypeScript with the necessary type information.

Using Declaration Files in a TypeScript Project

TypeScript automatically discovers declaration files when they are placed in specific locations. For example, if you place your .d.ts file next to your JavaScript file, TypeScript will find it. You can also include them using the include or files options in your tsconfig.json file.

In this example, the tsconfig.json includes all TypeScript files in the src directory and all declaration files in the types directory.

Using Third-Party Declaration Files

Many popular JavaScript libraries already have existing declaration files available. These can be installed via npm using the @types scope. For example, to install the declaration files for jQuery, you can run:

Once installed, TypeScript will automatically pick up the types from the installed @types package, enhancing your development experience with better type safety and IntelliSense.