What is the purpose of the declare keyword in TypeScript?

What is the purpose of the declare keyword in TypeScript?

I’m trying to understand the meaning of the declare keyword in TypeScript. For example, I have the following two lines:

type Callback = (err: Error | String, data: Array<CalledBackData>) => void

vs.

declare type Callback = (err: Error | String, data: Array<CalledBackData>) => void;

I can’t find documentation that explains the purpose of the declare keyword in TypeScript. What does it actually mean and when should it be used?

Hi

Purpose of declare for Declaring Global Types in TypeScript:

The declare keyword in TypeScript is used to indicate that a variable, type, or class exists but is defined elsewhere, typically outside the current file. This is often used in declaration files to describe types for external libraries or to define types that exist globally.

When you declare a type with declare, TypeScript understands that the type or variable is defined elsewhere, and it doesn’t need to worry about its implementation. In your example, declaring type Callback would tell TypeScript that the Callback type is defined elsewhere, and it doesn’t need to perform any checks on its definition.

I hope I was able to help you :slight_smile:

Usage of declare with TypeScript Global Variables: The declare keyword can also be used when defining global variables that TypeScript doesn’t automatically recognize. For example, when working with external JavaScript libraries or objects added dynamically, declare allows you to declare types for those objects.

It essentially informs TypeScript that the object exists but doesn’t provide its definition, enabling type checking and autocompletion for global variables or types. In your case, if Callback is used globally in a project, the declare keyword could be necessary to ensure TypeScript recognizes its type.

In cases where you’re integrating third-party code or working with an existing codebase where certain types or variables are declared outside the current TypeScript project, the declare keyword ensures that no TypeScript compilation errors occur.

For instance, if you want TypeScript to accept the Callback type from an external source but don’t have the full implementation in the current file, you would use declare to let TypeScript know that it exists but isn’t defined in the current context.