Member preview

Learning TypeScript 06 — Declaration files

At this point, we have talked about a lot of different things related to TypeScript.

But now, we need to understand how to be able to work with JavaScript libraries with our TypeScript code.

And that is really easy thanks to the ‘declaration files’ because these files tell to TypeScripthow the libraries are made and how are their structures.

But can I work without declaration files?

Sure, you can. This is an example of a code that is loading an external library.

In the most of the cases if you load the library like import * as NAME from 'path' it will work but are not going to be able to know anything from the library.

If you have problems you can try something like this.

But yes, this is ugly.

Working with declaration files

We are lucky to have a huge community and declaration files are in a constant evolution. Thanks to that we have a lot of declaration files for libraries, and in general, is not going to be a problem.

There are two scenarios where we can find declaration files for our libraries.

  • The library includes a ‘.d.ts’ (declaration file)

In this scenario, the library will just work as any TypeScript library, don’t worry and keep working on your project.

  • The library does not include a ‘.d.ts’ but there is a typing in npm.

If you’re not sure about this just go to npm website and search for `@types/name-of-library`

Probably you’re going to find your library.

But, maybe you’re not lucky and nobody has created it before… or you have your own library. It’s time to generate a d.ts

Generating our own declaration files

If you want to create your own files, the best is to follow the official docs by example.

Let’s see some examples:

You can declare a variable or a function:

Or you can declare an entire namespace:

To do that for big libraries could be really, slow. But there are tools to try to generate the declaration file automatically.

You can use Dts-Gen from Microsoft.

I’ve searched for a library without typings, for this case, I’m going to use aku from Kiko Beats.

You can find the entire code here.

If I import the library, I don’t know anything about the library, everything is any for TypeScript.

But if I generate the typings with the tool mentioned before:

That’s cooool 👏🏼 now we can modify the generated file to add more accurate information.

You can find more info about this article in the official guide.
And info about why I’m doing this articles about TypeScript.
Let’s continue with the next chapter: Augmenting types.
And remember, feedback is welcome 🤙.