Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a reason to use the declare keyword in front of types and interfaces?

I have come across some code like this:

declare type A = { ... };
declare interface B { ... }

From searching for the declare keyword (and none of the hits pointed to me the TypeScript docs for some reason), declare is used when a variable exists in JavaScript and you need to reference it from TypeScript, so you declare to the compiler that this variable indeed exists.

All examples I have found that use this keyword use it like this: declare var a;

Why would I ever use it in front of a type or interface? Based on my understanding of declare, it is completely useless to do so, but the compiler doesn't give me any errors.

like image 535
pushkin Avatar asked Mar 07 '18 15:03

pushkin


People also ask

When should you use the declare keyword?

The declare keyword in TypeScript is used for the Ambient declaration of variables or for methods. Ambient Declarations is like an import keyword. Which tells the compiler that the source exists in another file.

What is the purpose of declare?

declare is used to tell the compiler "this thing (usually a variable) exists already, and therefore can be referenced by other code, also there is no need to compile this statement into any JavaScript". Common Use Case: You add a reference to your web page to a JavaScript file that the compiler knows nothing about.

What is declare interface?

The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface. The StockWatcher interface and the structure of an interface definition.

What is declare class in TypeScript?

declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two . ts files that compile to two . js files and both are included via script tags in a webpage).


1 Answers

Looks like I just found out why.

From this github issue:

declare should be optional on type aliases and interfaces.

declare type and declare interface are identical to type and interface

Since we already shipped type aliases this way, people have had to write declare type a bunch of times. We could break them and say "Write type, not declare type", but that would be a massive break for no real reason.

In summary, there is no reason to use declare for types and interfaces.

like image 165
pushkin Avatar answered Sep 19 '22 09:09

pushkin