Power of declare Keyword in TypeScript: Complete Guide

Robin
Updated on March 3, 2023

TypeScript is a superset of JavaScript that provides static typing, making it easier to catch errors and bugs during development. One way to provide type information to TypeScript is by using the declare keyword.

The 'declare' keyword tells the TypeScript compiler that a variable or function exists, but its implementation will be provided by another JavaScript file or library at runtime.

In this blog post, we will explore the power of the 'declare' keyword in TypeScript and how it can be used for better external library integration and TypeScript development.

What is declare Keyword in TypeScript?

In TypeScript, the declare keyword is used to declare the type of a variable, function, class, or module without actually defining its implementation. This keyword provides information to the TypeScript compiler about a type that is already available outside of the current TypeScript file.

In other words, it is used to describe the shape of values that are not defined in TypeScript.

Why Use the declare Keyword?

The declare keyword is useful in scenarios where you are working with external JavaScript libraries that don't have TypeScript definitions.

In such cases, TypeScript does not know about the types and interfaces provided by these external libraries, and you may end up with errors during compilation or runtime.

By using the declare keyword, you can tell TypeScript about the types and interfaces of external libraries, making it possible to take advantage of TypeScript's powerful type-checking and code completion features.

Also Read: Mastering Type Casting in TypeScript: A Complete Guide

Using the 'declare' Keyword in TypeScript

You have learned what this keyword is and why you should use this. Now let's see how to use the declare keyword to create some types of variables, functions, classes, and modules.

How to Declare Global Variables

To add the type definition for a variable that exists outside of the current TypeScript file, use the declare keyword followed by the name of that variable with its type.

For example, let's say we have an external JavaScript library that defines a global variable called myGlobalVar but TypeScript has no idea about it and what type of data this variable stores.

          const myGlobalVar = "Hello, world!";
        

To use this variable in TypeScript, we need to declare its type using the declare keyword. You can do it by following this syntax:

          declare const myGlobalVar: string;
        

This tells the TypeScript compiler that there is a variable named myGlobalVar of type string, the above syntax won't create the variable here.

How to Declare Global Function

You can also use this keyword to create a function type for a function. Use the following syntax to declare the function definitions:

          declare function calculateSum(num1: number, num2: number): number;
        

This declares a function named calculateSum that takes in two parameters of type number and returns a value of type number. It doesn't create that function.

          function calculateSum(num1, num2) {
  return num1 + num2;
}
        

This calculateSum() function already exists in another JavaScript file. You are just adding a type to this function so that you can use this function in your TypeScript file.

How to Declare Class

When you want to add a type definition of a class, you will only write the structure of that class without implementing its methods.

Let's see an example:

          declare class Person {
  private id: number;
  private name: string;

  constructor(id: number, name: string);

  getBio(): string;
}
        

In this example, I am declaring a class called Person, which has two private properties id and name, a constructor that takes in two parameters id and name, and a method called myMethod.

Note that we are not providing an implementation for the class or its methods - we are simply declaring its existence and its shape.

Once you have declared the class using the declare keyword, you can use it in your TypeScript code as you would any other class.

          const john = new MyClass(1, "John");
john.getBio();
        

Also Read: TypeScript never Type: In-depth Explanation with Examples

Using declare Keyword with External Libraries in TypeScript

The declare keyword is very useful when you want to use an external library in your TypeScript project that doesn't have a type declaration file. Without this declaration file, TypeScript won't understand what variables and functions are available in that library.

In such cases, you can create a separate .d.ts file that declares the necessary types and interfaces for the external library using the declare keyword.

For example, you want to add a package to your TypeScript project called myPackage but it doesn't have the TypeScript definitions. You can create your own type definition file for that package.

Create a types.d.ts file in the root of your project and add the following code:

          declare module "myPackage"
        

After saving this file, you can import and use myPackage in any TypeScript file. I won't give any errors.

          import myPackage from "myPackage"
        

But there is a problem. The type of this package will be any therefore, you won't get any TypeScript support. To solve this problem, you can also add types for variables and functions that this package has.

          declare module "myPackage" {
    export const PI: number
    
    export function getRandom(min: number, max: number): number
}
        

When you add types for variables and functions of a package, you can import those variables and functions into your project. TypeScript will give you suggestions for those.

          import { PI, getRandom } from "myPackage"
        

Now, TypeScript knows that the type of PI is a number and, getRandom() function accepts 2 arguments of type number and also returns a number because you have added the types for this package.

Conclusion

You saw how to define global types using the declare keyword. With this keyword, you can declare the shape of external classes, functions, variables, and modules, and use them in your TypeScript code without worrying about type errors.

So next time you encounter an external library or API without TypeScript definitions, don't fret - just use the declare keyword and enjoy the benefits of working with TypeScript!

Related Posts