...

/

Understanding TypeScript Declaration Files

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 signatures
declare function trace(arg: string | number | boolean); // function that can take a string, number or boolean argument
declare function trace(arg: { id: number; name: string }); // function that takes an object with id and name properties as argument
TypeScript function with different signatures

Here, we have a function named trace that is declared twice:

  • Line 3: The first time is with a single parameter named arg of type string, number, or boolean.

  • 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:

Press + to interact
declaration_file_samples.ts
declaration_file_typing.d.ts
tsconfig.json
// This code calls the trace function with different arguments
trace("trace with string"); // calls the trace function with a string argument
trace(true); // calls the trace function with a boolean argument
trace(1); // calls the trace function with a number argument
trace({ 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 function
declare module FirstNamespace {
module SecondNamespace {
module ThirdNamespace {
function log(msg: string); // function to log a message
}
}
}
TypeScript module with nested namespaces and a function

Here, we declare a module named FirstNamespace that exposes a module named SecondNamespace, which, in turn, exposes a third module named ...