Using Declaration Files in TypeScript

Learn how to use declaration files in TypeScript to declare global variables and solve compilation errors.

Declaration files

A declaration file is a special type of file used by the TypeScript compiler. It is only used during the compilation step and is used as a sort of reference file to describe JavaScript. Declaration files are similar to the header files used in C or C++ or the interfaces used in Java. They simply describe the structure of available functions and properties but do not provide an implementation. We will take a look at these declaration files, what they are, and how to write them.

Global variables

Most modern websites use some sort of server engine to generate the HTML pages that we use. If familiar with the Microsoft stack of technologies, then we will know that ASP.NET MVCModel-View-Controller is a very popular server-side rendering engine. As a Node developer, we may be using one of the popular Node packages to help construct web pages through templates, such as Jade, Handlebars, or Embedded JavaScript (EJS). Within these templating engines, we may sometimes include some JavaScript within the rendered HTML as a result of our server-side logic. As an example of this, let’s assume that we keep a list of contact email addresses on our server and then surface them through a global variable as follows:

Get hands-on with 1200+ tech skills courses.