...

/

Finding and Writing Declaration Files

Finding and Writing Declaration Files

Learn about declaration files and how to find and write them in TypeScript projects.

Finding declaration files

Now that we know what a declaration file is, how do we find one that matches the JavaScript library that we are trying to use? Soon after TypeScript was released, Boris Yankov set up a GitHub repository to house TypeScript declaration files for third-party libraries. This repository, named Definitely Typed, quickly became very popular and is now the go-to repository for declaration files.

One of the major issues that needed to be addressed in relation to declaration files was the need to match a particular JavaScript library version with the Definitely Typed version that matched that release. The community has, over time, built a number of command-line tools to help with this, including tsd, typings, and NuGet extensions.

As of version 2.0 of TypeScript, we are able to use npm to install declaration files. As an example of this, let’s install the underscore package and its corresponding types as follows:

npm install underscore
npm install @types/underscore --save-dev

Here, we use npm to install the JavaScript library underscore, and then we use npm to install the corresponding declaration files by prefixing the library name with @types/.

In fact, if we attempt to use a library without installing the associated @types declaration files, the TypeScript compiler will generate the following error.

Could not find a declaration file for module 'underscore'
Try `npm i --save-dev @types/underscore` if it exists or add a new declaration (.d.ts) file containing
...