Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Type declarations – .d.ts

Sometimes, we will need to consume an existing JavaScript file, but we will not be able to migrate it to TypeScript. A common example of this scenario is when we consume a third-party JavaScript library.

If the library is open source, we could contribute to it by migrating it to TypeScript. However, sometimes, using TypeScript might not align with the preferences of the library authors, or the migration may require a significant amount of work. TypeScript solves this problem by allowing us to create special kinds of files known as type declarations or type definitions.

In the previous chapter, we learned that, by default, TypeScript includes a  lib.d.ts file that provides interface declarations for the built-in JavaScript objects, as well as the DOM and BOM APIs.

The type definition files contain the type declarations of third-party libraries. These files facilitate the integration between the existing JavaScript libraries and TypeScript.

To take advantage of all the TypeScript features while consuming a JavaScript library, we need to install the type definition file of such library. Fortunately, we don't need to create the type definition files by hand, because there is an open source project known as DefinitelyTyped that already contains some type definition files for many of the existing JavaScript libraries.

In the early days of TypeScript development, developers had to manually download and install the type definition files from the DefinitelyTyped project website, but those days are long gone and today we can use the node package manager (npm) to install and manage the type definition files required by our TypeScript application.

We will learn how to work with declaration files in Chapter 9 , Automating Your Development Workflow.