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:
// This code declares two TypeScript functions with different signaturesdeclare function trace(arg: string | number | boolean); // function that can take a string, number or boolean argumentdeclare function trace(arg: { id: number; name: string }); // function that takes an object with id and name properties as argument
Here, we have a function named trace
that is declared twice:
-
Line 3: The first time is with a single parameter named
arg
of typestring
,number
, orboolean
. -
Line 4: The second time is with the same
arg
parameter, which is a custom type.
This overloaded declaration allows for all of the following valid code:
// This code calls the trace function with different argumentstrace("trace with string"); // calls the trace function with a string argumenttrace(true); // calls the trace function with a boolean argumenttrace(1); // calls the trace function with a number argumenttrace({ id: 1, name: "test" }); // calls the trace function with an object argument
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:
// This code declares a TypeScript module with nested namespaces and a functiondeclare module FirstNamespace {module SecondNamespace {module ThirdNamespace {function log(msg: string); // function to log a message}}}
Here, we declare a module named FirstNamespace
that exposes a
module named SecondNamespace
, which, in turn, exposes a third module named
...