DEV Community

Rakan
Rakan

Posted on

Type Declaration Files

Type Declaration Files are files that describe the whole API of a library that was written in Javascript. These files are the magic behind TypeScript.

Let's break it down with a simple example:
Suppose there is a JavaScript library called mathLibrary.js with the following code:

const add = (a, b) => {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

If we try to use this library in a TypeScript file, we will get an error saying that add function doesn't exist. This is because TypeScript doesn't know anything about this library (because it's written in JavaScript without any type annotations). So, we need to create a type declaration file for this library. Let's call it mathLibrary.d.ts. It will look like this:

declare function add(a: number, b: number): number;
Enter fullscreen mode Exit fullscreen mode

Now, when we try to use this library in a TypeScript file, we will not get any errors. This is because TypeScript now knows about this library and its functions. It knows that add function takes 2 numbers and returns a number. So, if we try to pass a string, it will show an error.

Typescript depends on type declaration files heavily. It's what makes TypeScript so powerful. If you do npm install typescript, you will see that it comes with a lot of type declaration files ".d.ts" files in the node_modules.

Note: There is a tool called DefinitelyTyped which has a lot of type declaration files for popular JavaScript libraries. You can install them using npm install @types/<library-name>. For example, if you want to install type declaration files for Googlemaps JS library, you can do npm install @types/googlemaps after that TypeScript will automatically find the type declaration files in the node_modules/@types folder and use them to check your code for errors.

Resources:

Top comments (0)