Understanding TypeScript Declaration Files
Learn about function overloading, namespaces, classes, statics, abstracts, generics, and declarations.
The declaration files use the declare and module keywords to define objects and namespaces. We can use interfaces in the same way that we do within TypeScript in order to define custom types for variables. Declaration files allow us to use the same syntax that we would in TypeScript to describe types. These types can be used everywhere types are used in normal TypeScript, including function overloading, type unions, classes, and optional properties.
Let’s take a quick look at these techniques with a few simple code samples to illustrate this feature further.
Function overloading
Declaration files allow for function overloads, where the same function can be declared with different arguments, as follows:
Here, we have a function named trace that is declared twice:
-
Line 3: The first time is with a single parameter named
argof typestring,number, orboolean. -
Line 4: The second time is with the same
argparameter, which is a custom type.
This overloaded declaration allows for all of the following valid code:
Here, we have exercised the various combinations of arguments that are allowed by our function overloads.
Nested namespaces
Declaration files allow for module names to be nested. This, in turn, translates to nested namespaces:
Here, we declare a module named FirstNamespace that exposes a
module named SecondNamespace, which, in turn, exposes a third module named
...