Ole Ole - 1 month ago 6
TypeScript Question

Simple example of the construction and application of a .d.ts file?

I'm reading through this documentation trying to understand the purpose of TypeScript

files or declaration files:

When using an external JavaScript library, or new host API, you’ll need to use a declaration file (.d.ts) to describe the shape of that library.

Can someone please provide a simple example of what that means and how to apply it? The document does it, but it just seems like there's a simpler way to explain it. For example if I wanted to use moment.js with TypeScript then I would need the following

But Why do I need the file? In other words why can't I just import and use
without the


The stackoverflow documentation has a nice overview on how to install declaration libraries.

For moment specifically, you will just have to run typings install --global dt~moment ("install the global declaration file of moment from the source Definitely Typed").

The reason you need a declaration file, is because the external library is probably not written in typescript. As a result, you have to define what the api of the library looks like, so typescript knows roughly what is available.

The easiest declaration file would look something like this:


declare module 'moment'

This will allow you to use the moment library however you want, but you won't have any of the juicy autocomplete or typechecking available for any of the functions of this library. However, typechecking for an external module is extremely helpful, as you probably aren't very familiar with the api, compared to the code you wrote yourself.