Q . What does 'declare' do in 'export declare class Actions'?

Mike Tyson. asked, Jul 04 ' 2018

Why do we need the declare in the statement?

export declare class Actions {


declare var <variable name>
  • declare
  • variable
  • angular2
  • declare-keyword-angular

2 Answers

Declare vs. var

var creates a new variable. declare is used to tell TypeScript that the variable has been created elsewhere. If you use declare, nothing is added to the JavaScript that is generated - it is simply a hint to the compiler.

For example, if you use an external script that defines var externalModule, you would use declare var externalModule to hint to the TypeScript compiler that externalModule has already been set up

To understand this, you have to first understand the "declare" keyword.

Here is a good explanation from Gil Fink's Blog:

The TypeScript declare keyword is used to declare variables that may not have originated from a TypeScript file.

For example, lets imagine that we have a library called myLibrary that doesn’t have a TypeScript declaration file and have a namespace called myLibrary in the global namespace. If you want to use that library in your TypeScript code, you can use the following code:

declare var myLibrary;

The type that the TypeScript runtime will give to myLibrary variable is the any type. The problem here is that you won’t have Intellisense for that variable in design time but you will be able to use the library in your code. Another option to have the same behavior without using the declare keyword is just using a variable with the any type:

var myLibrary: any;

Both of the code examples will result in the same JavaScript output but the declare example is more readable and expresses an ambient declaration.

So after you understand the "declare" keyword, go back to wherever you find the

export declare class Action{

The class's real implementation is probably in somewhere else—maybe a .js file.

Leave a Ansewer